//index.js
//获取应用实例
var app = getApp()
var common = require("../../common/common.js")
var BLELocker = require('../../common/BLELocker.js')
var commonUtil = require('../../utils/commonUtil');

//常量数据配置
var ConstantData = require('../../common/constant_data.js')
var colonyBlue = require("colony_blue.js")
var statistic = require("statistic.js")
var noDepositLease = require("no_deposit_lease.js")
var util = require('../../utils/util.js');
var connectUtil = require('../../utils/ble-dfu/connect.js');
var downloadUtil = require('../../utils/ble-dfu/download.js');

Page({
  data: {
    isSlide:'',
    hand_img: 'hand_img1',
    bubble_img: 'bubble_img1',
    phoneAuthStatus: false,
    showMaintPlatform: false,
    showUseOtherMini: false,
    onLoadFlg: 0,
    statusBarHeight: app.globalData.statusBarHeight,
    navBarHeight: app.globalData.navBarHeight,
    motto: 'e家康护',
    showTipsPopup: false,
    beforeLeaseTipTitle: '欢迎使用e家康护',
    beforeLeaseTipContent: '提示：距离上次使用十分钟前',
    beforeLeaseIsContinue: true,

    numPerPage: 10,
    pageNum: 1,
    payStatus: true,
    voiceTempFilePath: '/image/backSuc.mp3',
    duanyuyin: '/image/duanyuyin.mp3',
    yuyinzujie: '/image/successyuyin.mp3',
    userInfo: {},
    showDialog: false, //展示弹窗
    autoPlay: false, // 租赁自动打开扫码
    showyijia: false,
    appInfo: {
      logoUrl: '../../image/logo.png',
      title: '使用微信内置地图查看API定位'
    },
    depositAutoBack: false,
    iconImgs: {
      subscribe_equ: '../../image/reservation_icon.png',
      care_lease: 'https://litemall-admin-001.oss-cn-hangzhou.aliyuncs.com/1705467773511143424.png',
      care_lease_admin: 'https://litemall-admin-001.oss-cn-hangzhou.aliyuncs.com/1705467908576120832.png',
      rent_static: 'https://litemall-admin-001.oss-cn-hangzhou.aliyuncs.com/1705468093414903808.png',
      admin: 'https://litemall-admin-001.oss-cn-hangzhou.aliyuncs.com/1705468259563868160.png'
    },
    miniImg: {
      chair_insert_style: ConstantData.CONSTATNT_DATA.BASE_URL_IMG + '/mini/chair_insert_style.jpg',
      kaoyou: ConstantData.CONSTATNT_DATA.BASE_URL_IMG + '/mini/kaoyou.png',
      short_box: ConstantData.CONSTATNT_DATA.BASE_URL_IMG + '/mini/short_box.png',
      long_box: ConstantData.CONSTATNT_DATA.BASE_URL_IMG + '/mini/long_box.png',
      temp_time_card: ConstantData.CONSTATNT_DATA.BASE_URL_IMG + '/mini/temp_time_card.jpg',
      use_tip_img_1: ConstantData.CONSTATNT_DATA.BASE_URL_IMG + '/mini/use-tip-img-1.png',
      use_tip_img_2: ConstantData.CONSTATNT_DATA.BASE_URL_IMG + '/mini/use-tip-img-2.png',
      use_tip_img_3: ConstantData.CONSTATNT_DATA.BASE_URL_IMG + '/mini/use-tip-img-3.png',
      homeBannerImg: ConstantData.CONSTATNT_DATA.BASE_URL + '/mini/home-banner.png',
      banner1: ConstantData.CONSTATNT_DATA.BASE_URL + '/mini/sanglongjia/banner1.png',
      banner2: ConstantData.CONSTATNT_DATA.BASE_URL + '/mini/sanglongjia/banner2.png',
      icPlus1: ConstantData.CONSTATNT_DATA.BASE_URL + '/mini/sanglongjia/2023/ic-plus1.png',
      icPlus2: ConstantData.CONSTATNT_DATA.BASE_URL + '/mini/sanglongjia/2023/ic-plus2.png',
      icFoot: ConstantData.CONSTATNT_DATA.BASE_URL + '/mini/sanglongjia/2023/ic-foot.png',
      icNear: ConstantData.CONSTATNT_DATA.BASE_URL + '/mini/sanglongjia/2023/ic-near.png',
      icService: ConstantData.CONSTATNT_DATA.BASE_URL + '/mini/sanglongjia/2023/ic-service.png',
      icOther: ConstantData.CONSTATNT_DATA.BASE_URL + '/mini/sanglongjia/2023/ic-other.png',
      icMe: ConstantData.CONSTATNT_DATA.BASE_URL + '/mini/sanglongjia/2023/ic-me.png',
      icMbtn: ConstantData.CONSTATNT_DATA.BASE_URL + '/mini/sanglongjia/2023/ic-mbtn.png',
      icScan: ConstantData.CONSTATNT_DATA.BASE_URL + '/mini/sanglongjia/2023/ic-scan.png',
      icDingdan: ConstantData.CONSTATNT_DATA.BASE_URL + '/mini/sanglongjia/2023/ic-dingdan.png',
      icYajin: ConstantData.CONSTATNT_DATA.BASE_URL + '/mini/sanglongjia/2023/ic-yajin.png',
      icLease: ConstantData.CONSTATNT_DATA.BASE_URL + '/mini/sanglongjia/2023/ic-lease.png',
      icReturn: ConstantData.CONSTATNT_DATA.BASE_URL + '/mini/sanglongjia/2023/ic-return.png',
      icM1: ConstantData.CONSTATNT_DATA.BASE_URL + '/mini/sanglongjia/2023/ic-m1.png',
      icM2: ConstantData.CONSTATNT_DATA.BASE_URL + '/mini/sanglongjia/2023/ic-m2.png',
      icM3: ConstantData.CONSTATNT_DATA.BASE_URL + '/mini/sanglongjia/2023/ic-m3.png',
      icM4: ConstantData.CONSTATNT_DATA.BASE_URL + '/mini/sanglongjia/2023/ic-m4.png',
      icM5: ConstantData.CONSTATNT_DATA.BASE_URL + '/mini/sanglongjia/2023/ic-m5.png',
      icClose: ConstantData.CONSTATNT_DATA.BASE_URL + '/mini/sanglongjia/2023/ic-close.png',
    },
    showDialog1: false,
    showDialog2: false,
    showDialog3: false,
    showOtherPopup: false,
    showModalStatus: false, //收费规则展示,地图需要隐藏
    mapShowStatus: true, //地图是否显示
    showEquBusiStatus: false,
    showEquBusiId: 0, //展示的商家的归位桩情况
    careShowStat: false,
    managerShowStat: false,
    ruleInfo: "",
    markers: [],
    equTitle: "e家康护",
    alertBoxStatus: false,
    alertBoxBtnName: '确  定',
    callServiceBoxStatus: false,
    authStr: '',
    serviceId: '',
    deviceId: '',
    discoveryCount: 0,
    scanStatus: false,
    loginStatus: true,
    connectDesc: "蓝牙设备开始连接...",
    openLockLeaseOptStatus: true, //开锁租赁按钮操作控制
    checkboxStatus: 'checkboxSelected',
    checkboxImg: "checkboxSelected.png",
    tipStatus: false,
    tipBtnName: "确 定",
    tipContent: "",
    curBlueName: "", //当前连接的蓝牙名称
    systemInfo: {},
    hideIsDisconnectStat: true, //隐藏不进行关闭蓝牙，true关闭，false不关闭
    bindUserListStatus: false, //绑定的用户列表
    agentLeaseSelStatus: false, //最终是否确认租赁选择框
    bindUserList: [],
    bindDefaultValue: [0],
    selBindUserId: 0, //选择的绑定的用户id
    selBindUser: {},
    leftTimeLenStr: '',
    noPayTimeTipStatus: false,
    noPayTimeLenStr: '',
    noLeaseTipInfo: '',
    cancelAgentSelLeaseStatus: true,
    bindUserType: 0, //绑定用户的类型0普通，1卡绑定用户，2门诊爱心绑定用户
    payDepositStat: false, //支付押金状态false未支付，ture支付成功
    controls: [],
    many95DataInterval: 2000, //多个95间隔时间 单位ms
    blue95Interval: 15000, //95和订单间隔时间 单位ms
    qrcContent: '', //二维码内容
    pt: '', //跳转过来的页面
    connectReqNum: 0, //蓝牙连接请求序列号
    isCheckSession: 0, //0可以进行changePass，1不可以进行changePass
    serverBasiceConfig: null, //服务的配置信息
    connectLogSwitch: 0, //蓝牙连接请求0开，1关
    payDepositBtnStatus: true,
    payDepositBtnTxt: "去缴纳",
    callConsumePhoneBoxStatus: false, //拨打电话的提示框
    callPhoneTipContent: "", //拨打电话的提示内容
    mainConsumerPhone: "", //点击拨打的客服电话
    phoneSetLocationHelpImg: "", //提示用户修改定位信息的帮助图片
    homeDepositTime: "", //首页"去退押金"后面的说明文字描述
    serviceUuid: '',
    homingFEC7: '',
    homingFEC8: '',
    homingFEC9: '',
    messageBtnFlg: false,
    statisticBtnFlg: false,
    toPayDeposit: false,
    optAdminBtnFlg: false,
    phoneAuthBtt: '',
    refund: 0,
    refundTip: 0,
    isRefundTip: 0,
    isBackChairStatus: false, //当前是需进行归还操作
    noDepositFail: false, //免押授权失败
    isPayDeposit: false, //true支付过押金,false未支付押金
    colonyConFail: 0, //蓝牙集群连接失败的次数
    noRfidLeaseStatus: false,
    pileResetStat: false, //发送85进行开锁复位
    phoneType: "",
    isJudgeInsertSwitch: true,
    noDepositBackFlg: true,
    isAllowNoDeposit: false, //不允许免押
    picTip: '',
    wxScore: 600,
    // isReturn:false,
    read: true,
    // openLockLeftSeconds: 20,//开锁倒计时
    openLockStat: false,
    phoneNoDirFlg: false, //iPhone oppo vivo huawei xiaomi之外的手机
    isFirstJudge: true,
    isReturn: 0,
    pageName: 'index',
    conErrDesc: '',
    connectType: '',
    loading_desc: '设备连接中',
    modal: {
      // modal_show: true,
      title: '温馨提示', //默认弹框标题
      desc_center: true, //内容居中显示
      // open_ble_auth_show: true,
      // confirm: true,
      desc: 'xxxxxxxx',
      // desc_mini: '85backTimeout(30001)',
      // contact: true,
      // cancel: true,
    },
    directFirstIsFail: false, //安卓蓝牙连接第一次是否失败
    stopConnect: false, //用户中断连接
    scanningCode: false, //扫码按钮的防呆
    retryConBtnCss: "modal-btn-green",
    latticeCabinetData: null, //格子柜信息
    lockTypeSeledId: 0, //直行锁选择的设备类型id
    checkPayStatusInterval: null,
    isPayDepositSuccess: false,
    isSubOffical: true,
    officalSubImg: ConstantData.CONSTATNT_DATA.OFFICAL_SUB_IMG_URL,

    current: 0, //当前所在页面的 index
    indicatorDots: true, //是否显示面板指示点
    autoplay: true, //是否自动切换
    interval: 2000, //自动切换时间间隔
    duration: 800, //滑动动画时长
    circular: true, //是否采用衔接滑动
    imgUrls: [],
    homeAdImg: "https://www.ejiakanghu.cn/images/mini_tip/home_ad_top.png?v=1.0&t=" + new Date().getTime(),
    newHeadImg: "",
    menuList: [],
    menuPageSize: 5, // 每页菜单数量
    menuTotalPage: 0, // 菜单总分页数
    isConnected: true,

    unRentStatus: false,
    unRentDesc: '',
    alertUnRentBox: '我知道了',
    hasNoBack: false,
    hasSubOrder: false,
  },

  toPhoneLogin: function () {
    wx.navigateTo({
      url: '../login/login',
    })
  },

  toService: function () {
    wx.navigateTo({
      url: '../../pkgBak/pages/help/help',
    })
  },
  //关闭平台提醒 
  closePlatformManitExceptionTip() {
    this.setData({
      showMaintPlatform: false
    })
  },
  //关闭提示使用其他小程序提示 
  closeUseOtherMiniTip() {
    this.setData({
      showUseOtherMini: false
    })
  },

  onConfirmDialog2: function () {
    this.setData({
      showDialog2: false
    });
    this.setData({
      showDialog3: true
    });
  },

  openOtherPopup: function () {
    this.setData({
      showOtherPopup: true
    });
  },

  closeOtherPopup: function () {
    this.setData({
      showOtherPopup: false
    });
  },

  onLoadOfficial: function (e) {
    console.log('关注公众号组件加载成功', e)
  },

  onErrorOfficial: function (e) {
    console.log('关注公众号组件加载失败', e)
  },

  /**
   * 跳转到关注公众号的页面
   */
  goFollowMp: function () {
    app.goFollowMp(-200001, '关注公众号-首页')
  },

  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../location/location'
    })
  },
  //16进制字符串转Uint8Array
  hexStrToUint8Array(hexStr) {
    var uint8Array = new Uint8Array(hexStr.match(/[\da-f]{2}/gi).map(function (h) {
      return parseInt(h, 16);
    }));
    return uint8Array;
  },
  contacted() { // mark: 进入客服咨询
    const baseVer = wx.getSystemInfoSync().SDKVersion
    let rst = commonUtil.compareVersion(baseVer, '2.19.0') // mark: 客服接入
    if (rst >= 0) {
      wx.openCustomerServiceChat({
        extInfo: {
          url: 'https://work.weixin.qq.com/kfid/kfced14b7ce957b5acb'
        },
        corpId: 'wwd11a8d1fbe4cdae3',
        success(res) {
          console.log("接入企业微信客服:", res)
        },
        fail: function (err) {
          console.error("接入企业微信客服:", err)
        }
      })
    } else {
      wx.navigateTo({
        url: '../callCenter/callCenter',
      })
    }
  },
  openConfirm: function () {
    this.setData({
      showDialog: true
    });
  },
  closeConfirm: function () {
    this.setData({
      showDialog: false
    });
    this.scan()
  },
  closeZhezhao: function () {
    this.setData({
      showDialog: false
    });
  },
  tapTipsGreenBtn() {
    var that = this;
    that.setData({
      showTipsPopup: false
    })
  },
  tapTipsWhiteBtn() {
    var that = this;
    that.setData({
      showTipsPopup: false
    })
    //继续租赁   
    //将结果值改为正常，用户继续租赁
    that.data.conDevRes.data.rst = 0
    //处理返回数据并调用蓝牙连接
    that.handleConDevRes()
  },
  tapTipsCloseBtn() {
    var that = this;
    that.setData({
      showTipsPopup: false
    })
  },
  onLoad: function (options) {
    var that = this;
    //标记执行了onLoad事件
    that.data.procOnload = 1

    // 黑名单
    if (options.desc) {
      this.setData({
        unRentStatus: true,
        unRentDesc: options.desc
      })
    }
    // 租赁调用扫码
    if (options.autoPlay == 'true') {
      this.scan()
    }
    this.getNetwork()
    console.log("--------options-->", options)
    //获取服务的配置信息
    this.getBasicConfigInfo()
    if (app.systemInfo && app.systemInfo.brand) {
      this.setData({
        phoneInfo: app.systemInfo.brand + '-' + app.systemInfo.model + '-' + app.systemInfo.system
      })
    }
    var pt = options.pt
    if (pt != null && pt != undefined && pt != '') {
      this.data.pt = pt;
    }
    if (options.depositAutoBack) {
      this.data.depositAutoBack = true
    }

    //获取二维码内容
    var content = options.q;
    this.data.qrcContent = content
    // var content = "http://www.ejiakanghu.com.cn/device/12/c2hhbmdoYWlfZWF3aGp5eWxfMDE4ODA3ODE=";//todo
    //判断用户是否手机号登录，未登录跳转到登录页面,已登录的未支付的弹框输入要绑定的手机号，及备注信息，然后进行支付,
    //支付成功的,判断是否绑定过，未绑定过进行关系绑定，已绑定的直接提示已经绑定过
    app.scanTimeCardQrcodeHandle(content)

    if (content != undefined) {
      content = decodeURIComponent(content)
    }
    this.data.isScanQrc = false;
    this.data.isWxScanFlg = false; //是否微信扫一扫进入
    var qrc = null;
    if (content != undefined && content.indexOf(app.DEVICE_QRCODE_URL_PREFIX) == 0) {
      //使用微信扫码开始使用的时间
      this.data.startScanUseTime = new Date().getTime();
      //桩二维码
      this.data.qrcContent = content
      this.data.isScanQrc = true;
      this.data.isWxScanFlg = true;
      var rst = content.split('/');
      qrc = rst[rst.length - 1];
      let qrc_old = app.getScanQrcContent();
      console.log("------>>-------->>qrc_old", qrc_old)
      console.log("------>>-------->>qrc", qrc)
      if (qrc != qrc_old) {
        wx.removeStorageSync('blue_fail_time')
        wx.removeStorageSync('rfid_error_time')
        wx.removeStorageSync('insert_fail_time')
        wx.removeStorageSync('hook_fail_time')
        wx.removeStorageSync('has_opened_gprs')
        wx.removeStorageSync('no_eject_times')
        this.setData({
          isReturn: 0
        })
      }

      app.globalData.scan.qrc = qrc;
      //通过微信扫码进入得到的二维码内容
      app.globalData.wxScan.qrc = qrc;
      try {
        wx.setStorageSync('scan_qrc', qrc);
      } catch (e) {}

      console.log("-------------->content=", content);
    } else {
      that.data.scanningCode = false;
    }

    let user_id = wx.getStorageSync('user_id')
    let systeminfo = wx.getStorageSync('systeminfo')
    console.log('systeminfo------------>', systeminfo)
    let windowHeight = systeminfo.windowHeight - systeminfo.statusBarHeight
    that.setData({
      user_id: user_id,
      miniVer: ConstantData.CONSTATNT_DATA.MINI_VERSION,
      windowHeight: windowHeight
    })
    //onload 调用
    this.getShowControlsInfo()
    that.getRightBtns(1);
    app.executeRequest(function (header) {
      wx.showLoading({
        title: '加载中',
      })
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_user/is_con', //判断是否有未归还
        // url: 'http://localhost:8088/visfull-vbzd/lease_user/is_con', //判断是否有未归还        
        header: header,
        success: function (res) {
          console.warn("--是否直接连蓝牙", res, that.data.qrcContent, res);
          if (res.data.description === '未登录') {
            wx.setStorageSync('nophone', 1);
            app.globalData.loginData.nophone = 1;
          }
          let netErr = app.handleRes(res, that);
          console.log(99999, netErr)
          if (netErr) {
            that.data.scanningCode = false;
            that.setData({
              phoneAuthStatus: false
            })
            return
          }
          //已预约的数量
          that.data.subEquCount = res.data.subEquCount ? res.data.subEquCount : 0
          var rst = res.data.data;
          if (res.data.isBindPhone === true) {
            //已绑定
            wx.setStorageSync('nophone', 2);
            app.globalData.loginData.nophone = 2;
            that.setData({
              phoneAuthStatus: false
            })
          } else if (res.data.isBindPhone === false) {
            //未绑定手机号
            wx.setStorageSync('nophone', 1);
            app.globalData.loginData.nophone = 1;
            that.setData({
              phoneAuthStatus: true
            })
            // return;
          }
          if (res.data.noBack) {
            //未归还的
            wx.showLoading({
              // mask: true,
              title: '加载中...',
            })
            console.log("------noBack")
            wx.setStorageSync("user_no_back", res);
            that.setData({
              connectType: '归还'
            })
            //如果是微信扫桩二维码进入，直接连接归还
            if (qrc && pt != 'scan' && pt != 'blue_tip') {
              that.getDevIdAndConnect(qrc, 'resNoBack')
            } else if (pt != 'noback') {
              that.data.scanningCode = false;
            }
            return;
          } else if (res.data.noPay) {
            that.data.scanningCode = false;
            //未支付
            wx.showLoading({
              // mask: true,
              title: '加载中...',
            })
            console.log("------noPay")
            wx.setStorageSync("user_no_pay", res);
            console.log("----noback-------2")
            noDepositLease.getLeaseNoDepositInfo(app.globalData.appOnShowData, that);
            return;
          }
          wx.removeStorageSync('user_no_back');
          that.setData({
            connectType: '租借'
          })
          wx.removeStorageSync('user_no_pay');
          if (rst == 1 && qrc && pt != 'noback' && pt != 'scan' && pt != 'blue_tip') {
            that.getDevIdAndConnect(qrc, 'rst1');
            return;
          } else if (rst == 3) {
            //存在未归还设备提示，用户确认后直接连接
            that.data.isBackChairStatus = true
            if (qrc && pt != 'noback' && pt != 'scan' && pt != 'blue_tip') {
              that.getDevIdAndConnect(qrc, 'rst3');
              return;
            } else {
              that.data.scanningCode = false;
            }
          }
        },
        fail: function (res) {
          that.setData({
            phoneAuthStatus: false
          })
          app.handleRes(res, that);
        },
        complete:function(){
          wx.hideLoading()
        }
      });
    });
    if (pt == 'no_return_blue_timeout') {
      //扫码归还时连接超时，存在未归还记录进行弹框提示
      var desc = wx.getStorageSync("alertBoxTipContent")
      this.setData({
        loading_show: false,
        alertBoxStatus: true,
        alertBoxTipContent: desc,
        alertBoxBtnName: "确 定"
      })
      this.data.scanningCode = false;

    } else if (pt == 'nophone') {
      this.setData({
        phoneAuthStatus: true,
        phoneAuthBtt: 'record_user_deposit',
      })
      this.data.scanningCode = false;

    } else if (pt == 'scan' || pt == 'blue_tip') {
      var qrc = app.getScanQrcContent();
      if (qrc != '' && qrc != null && qrc != undefined) {
        console.warn('login页面登录成功后直接连接');
        this.getDevIdAndConnect(qrc, 'blueTip');
        return;
      } else {
        console.warn('login页面登录成功后调起摄像头');
        // this.scan();     
        return;
      }
    } else if (pt == 'complete') { //从归还成功页面跳转
      this.data.scanningCode = false;
      console.warn('归还成功后到首页什么都不操作');
      return;
    }

    wx.removeStorageSync('user_no_back');
    that.setData({
      connectType: '租借'
    })
    wx.removeStorageSync('user_no_pay');




  },
  //获取订单
  getApageLeaseRecord: function (lode) {
    if (!lode) {
      wx.showLoading({
        title: '加载中...',
        mask: true
      });
    }
    var that = this
    app.executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/wxmini/record_list',
        method: 'post',
        header: header,
        data: {
          numPerPage: that.data.numPerPage,
          pageNum: that.data.pageNum
        },
        success: function (res) {
          console.log("userRecordsList-->", res);
          if (lode) {
            that.data.leseList = []
          }
          if (res.data.result == 0) {
            var oldList = that.data.leseList || []
            var newList = oldList.concat(res.data.data.data)
            var isUseed=''
            newList.forEach(item => {
              if (typeof item.consumePrice == 'number') {
                item.consumePrice = item.consumePrice.toString().split('.')
              }
              if(item.stat == 0&&item.orderType != 1000){
                isUseed=1
              }
            })
            newList = newList.filter(item => {
              return item.orderType != 1000
            })

            if (res.data.data.pageNum * that.data.numPerPage >= res.data.data.total) {
              that.setData({
                loading: false,
                loadingComplete: true,
                leseList: newList,
                isUseed:isUseed
              });
            } else {
              that.setData({
                loading: true,
                loadingComplete: false,
                leseList: newList,
                isUseed:isUseed
              });
            }
          } else {
            wx.showToast({
              title: '获取失败'
            })
          }
        },
        complete() {
          getApp().hideLoading()
        }
      })

    })

  },
  //详情页面
  toDetail: function (e) {
    let data = e.currentTarget.dataset.data
    data = JSON.stringify({
      ...data
    })
    wx.navigateTo({
      url: '/pkgNew/pages/orderDetails/index?data=' + encodeURIComponent(data),
    })
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  bindscrolltolower: function () {
    var that = this;
    if (that.data.loading && !that.data.loadingComplete) {
      that.setData({
        pageNum: that.data.pageNum + 1, //每次触发上拉事件，把searchPageNum+1  
      });
      that.getApageLeaseRecord();
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  onShow: function (res) {
    this.setData({
      pageNum: 1,
    })
    
    if(app.globalData.devConnected) {
      BLELocker.disconnect('home706')
    } 
    if(app.globalData.timeoutConnectTimeout) {
      clearTimeout(app.globalData.timeoutConnectTimeout)
    }

    if (app.globalData.miniAuthSetting == null || app.globalData.miniAuthSetting["scope.bluetooth"] === false) {
      console.log("获取小程序授权信息")
      commonUtil.getMiniSetting()
    }
    app.globalData.gatewayUnlockFlg = false
    app.globalData.devConnected = false;
    app.globalData.isOpenLock = false;
    app.globalData._that = this;
    var nophone = app.getUserLoginNoPhone();
    if (this.data.scanningCode && nophone == 2) {
      this.setData({
        loading_show: true,
        loading_desc: '请稍候...',
        connectDesc: "请稍候...",
        pile_id: 0
      })
    }
    getApp().hideLoading();
    if (this.data.pt == 'noback') {
      console.log("--noback---scan qrcode--");
      this.data.pt = '';
      this.scan(true);
      return;
    }

    if (this.data.pt == 'noreturnequ') {
      this.data.pt = '';
      this.setData({
        isBackChairStatus: true,
        refund: 1
      });
      this.scan()
    }

    console.log("=====onShow", this.data.pt, this.data.isAllowNoDeposit, this.data.noDepositFail, app.globalData.userStay, app.globalData.devConnected, app.globalData.isOpenLock)
    console.log("---nophone=", nophone)
    var that = this
    //默认是租赁连接，归还成功后设置成false，可用于升级驱动
    app.globalData.isLeaseCon = true;

    if (nophone == null || nophone == undefined || nophone == 1) {
      this.setData({
        phoneAuthStatus: true,
        phoneAuthBtt: 'scan'
      });
      // return
    } else if (nophone == 2) {
      this.setData({
        phoneAuthStatus: false,
        phoneAuthBtt: ''
      });
    }
    console.log("---检查用户登录状态", nophone)

    that.checkUserSession()
    if (app.globalData.userStay) { //如果是从未归还页面过来的，则不跳转
      app.globalData.userStay = false;
      if (that.data.openning_show) {
        that.setData({
          openning_show: false
        })
      }
      return
    }

    let devIsCon = app.globalData.devConnected;
    if (devIsCon && app.globalData.isOpenLock) {
      console.log("----noback-------3")      
      noDepositLease.getLeaseNoDepositInfo(app.globalData.appOnShowData, that);
    } else if (this.data.isFirstJudge) {
      //onShow 爱心租赁按钮是否显示
      that.getRightBtns(this.data.procOnload);
    }



    if (this.data.payDepositStat && this.data.showModalStatus) {
      console.log("押金支付成功，需要保留提示弹框显示")
    } else {
      this.setData({
        mapShowStatus: true,
        payDepositStat: false
      })
    }

  },
  onReady: function () {
    var nophone = app.getUserLoginNoPhone();
    var that = this;
    if (!nophone || nophone == "1" || nophone === 1) {
      nophone = app.getUserLoginNoPhone();
      if (nophone && nophone == 2) {
        that.data.loginStatus = false
        that.data.scanStatus = true
      } else {
        that.data.loginStatus = true
        that.data.scanStatus = false
      }
    } else {
      that.data.loginStatus = false
      that.data.scanStatus = true
    }

    if (wx.openBluetoothAdapter) {} else {
      // 如果希望用户在最新版本的客户端上体验您的小程序,可以这样子提示
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。'
      });
    }

  },
  onHide: function () {
    let that = this;
    this.data.isFirstJudge = true
    this.data.trying = false
    clearTimeout(that.data.timerLoading);
    that.data.timerLoading = null;
    common.clearConTimeCountTimer('113');

    //关闭蓝牙连接
    if (this.data.hideIsDisconnectStat) {
      //是否关闭连接或者是否开锁中
    } else {
      return
    }

    console.log("onHide---->", this.data.openLockStat, app.globalData.isOpenLock, app.globalData.isConnecting);
    //openLockStat true正在开锁中,isOpenLock true免押跳转中，正在开锁中，isConnecting 设备开始连接标记
    if (!this.data.openLockStat && !app.globalData.isOpenLock) {
      that.clear85Timer();
      that.setData({
        showModalStatus: false, //收费规则提示的弹框
        callServiceBoxStatus: false, //缴纳押金的弹框
        openning_show: false, //开锁中的提示
      })
    }
    if (this.data.alertBoxStatus) {
      this.setData({
        alertBoxStatus: false
      })
    }
    if (that.data.modal.modal_show) {
      that.hideModal1();
    }
    this.data.qrcContent = '';
    this.setData({
      bindUserListStatus: false,
      callServiceBoxStatus: false,
      // showModalStatus:false,
      tipStatus: false,
      agentLeaseSelStatus: false,
      bindUserType: 0,
      isCheckSession: 0,
      payDepositBtnStatus: true,
      payDepositBtnTxt: "去缴纳",
      callConsumePhoneBoxStatus: false
    })
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log("-----------onUnload")
    this.data.depositAutoBack = false
    app.globalData.isConnecting = false;
    //关闭蓝牙连接
    BLELocker.disconnect('index552')
    this.recordBlueConnectError(ConstantData.err_type.page_unload, '首页退出');
  },
  regionchange: function () {

  },

  getRightBtns: function (onLoadFlg) {
    var that = this;
    that.data.isFirstJudge = false;
    that.setData({
      hasNoBack: false,
      hasSubOrder: false,
    })
    app.executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/time_card_patient/care_show', //判断是否有未归还
        header: header,
        success: function (res) {
          let netErr = app.handleRes(res, that);
          if (netErr) {
            return
          }
          if (res.data.blackUserStat == 10001) {
            that.setData({
              unRentStatus: true,
              unRentDesc: res.data.blackTipContent
            })
          }

          // 获取是否关注公众号变量
          if (res.data.isSubOffical != undefined && (res.data.isSubOffical == false || res.data.isSubOffical == true)) {
            app.globalData.isSubOffical = res.data.isSubOffical;
            console.log('是否关注公众号：' + app.globalData.isSubOffical);
          } else {
            app.globalData.isSubOffical = false;
            console.log('是否关注公众号：未下发变量');
          }
          // 记录展示关注公众号日志
          if (!app.globalData.isSubOffical) {
            app.recordShowMpLog(-200001, '关注公众号-首页')
          }

          //已预约的数量
          that.data.subEquCount = res.data.subCount ? res.data.subCount : 0

          var careShowFlg = res.data.data
          var manageShowFlg = res.data.authManageFlg
          var statisticCount = res.data.statisticVisit;
          var optAdminCount = res.data.adminVisit;
          let powerAdminFlg = res.data.powerAdminFlg;
          that.setData({
            manageShowFlg:manageShowFlg  
          })
          let menuList = [
            // {
            //   icon: ConstantData.CONSTATNT_DATA.BASE_URL + '/mini/sanglongjia/m1.png',
            //   name: '点击退押金',
            //   type: 'refund-deposit',
            // },
            // {
            //   icon: ConstantData.CONSTATNT_DATA.BASE_URL + '/mini/sanglongjia/m2.png',
            //   name: '查询归还位置',
            //   type: 'location-view',
            // },
            {
              icon: that.data.miniImg.icM1,
              bgColor: '#FEF5EF',
              name: '预约轮椅',
              type: 'subscribe-equ',
            }
          ]

          if (careShowFlg) {
            menuList.push({
              icon: that.data.miniImg.icM2,
              bgColor: '#FBEDF4',
              name: '帮代借',
              type: 'care-lease',
            })
          }

          if (manageShowFlg) {
            menuList.push({
              icon: that.data.miniImg.icM5,
              bgColor: '#F3FFF3',
              name: '帮代借管理',
              type: 'care-lease-admin',
            })
          }

          if (statisticCount > 0) {
            menuList.push({
              icon: that.data.miniImg.icM3,
              bgColor: '#FFE7E2',
              name: '租借统计',
              type: 'rent-static',
            })
          }

          if (optAdminCount > 0) {
            menuList.push({
              icon: that.data.miniImg.icM4,
              bgColor: '#DAECFE',
              name: '平台管理',
              type: 'admin',
            })
          }

          that.setData({
            menuTotalPage: Math.ceil(menuList.length / that.data.menuPageSize),
            menuList: menuList
          })

          //是否添加或去除管理按钮
          // that.getShowOutpatientIcon(careShowFlg, manageShowFlg, that.data.controls)
          if (res.data.subCount) {
            that.setData({
              hasSubOrder: true
            })
          }

          if (res.data.noBack && !that.data.isScanQrc) {
            wx.setStorageSync("user_no_back", res);
            that.setData({
              hasNoBack: true,
              hasSubOrder: false,
              connectType: '归还'
            })
            //未归还的
            if (that.data.pt != 'noback') { //200114 冯慧敏修改 在免押前就设置了openning_show为true，因此此处去掉openning_show的判断
              console.log("----noback-------4")
              noDepositLease.getLeaseNoDepositInfo(app.globalData.appOnShowData, that, onLoadFlg);
            }

            if (that.data.openning_show) {
              that.setData({
                openning_show: false
              })
            }

          } else if (res.data.noPay && !that.data.isScanQrc) {
            wx.setStorageSync("user_no_pay", res);
            //未支付
            if (that.data.pt != 'noreturnequ') {
              console.log("----noback-------5")
              noDepositLease.getLeaseNoDepositInfo(app.globalData.appOnShowData, that, onLoadFlg);
            } else if (that.data.openning_show) {
              that.setData({
                openning_show: false
              })
            }
          } else {
            console.log("--remove-careshow-noback")
            wx.removeStorageSync('user_no_back');
            that.setData({
              connectType: '租借',
              openning_desc: '【首页】正在查询支付/授权结果-809...'
            })
            that.recordBlueConnectError(ConstantData.err_type.deposit_query, '正在查询支付/授权结果...');
            wx.removeStorageSync('user_no_pay');
            console.log("----noback-------6")
            noDepositLease.getLeaseNoDepositInfo(app.globalData.appOnShowData, that, onLoadFlg);
          }
        },
        fail: function (res) {
          if (that.data.openning_show) {
            that.setData({
              openning_show: false
            })
          }
          app.handleRes(res, that);
        }
      })
    })

  },

  onSwiperChange(e) {
    const vm = this
    vm.setData({
      menuIndex: e.detail.current
    })
  },
  clickMenu(e) {
    let menuType = e.currentTarget.dataset.type
    if (menuType == 'refund-deposit') {
      this.toRefundDeposit()
      return
    }
    if (menuType == 'customer-service') {
      this.contacted()
      return
    }
    if (menuType == 'location-view') {
      this.toLocation()
      return
    }
    if (menuType == 'admin') {
      this.toVisitOptAdminInfo()
      return
    }
    if (menuType == 'rent-static') {
      this.toVisitStatisticInfo()
      return
    }
    if (menuType == 'care-lease') {
      let isManage=''
      if(this.data.manageShowFlg){
        isManage=1
      }
      this.outpatientCareLease(isManage)
      return
    }
    if (menuType == 'care-lease-admin') {
      this.outpatientCareManage()
      return
    }
    if (menuType == 'subscribe-equ') {
      this.toSubscribeEqu()
      return
    }
  },

  /**
   * 关闭弹框并断开蓝牙
   */
  closeModal() {
    app.globalData.isConnecting = false;
    BLELocker.disconnect('index562');
    this.hideModal1();
    this.setData({
      loading_show: false
    })
  },
  /**
   * 关闭连接中的框并中断蓝牙连接
   */
  closeLoading() {
    let that = this;
    if (that.data.timerLoading == null) {
      that.data.timerLoading = setTimeout(() => {
        clearTimeout(that.data.timerLoading);
        that.data.timerLoading = null;
        console.warn('index637关闭了连接中的框');
        that.setData({
          loading_show: false
        })
      }, 2500)
    } else {
      return;
    }
    BLELocker.disconnect('index632', 'stopConnect');
    that.recordBlueConnectError(10060, '用户中断连接');
    that.hideModal1();
    that.data.canceledConnect = true;
    that.data.stopConnect = true;
    that.setData({
      loading_desc: '正在断开连接，请稍候...'
    })
  },
  /**
   * 关闭弹框
   */
  hideModal1() {
    this.setData({
      modal: {
        modal_show: false,
        confirmSelType: false,
      }
    });
    this.data.modal.title = '温馨提示';
    this.data.modal.desc_mini = '';
    this.data.modal.desc_center = true;
    console.log('关闭弹框hidemodal1');
  },

  /**
   * 检测用户手机型号是否是iPhone huawei xiaomi oppo vivo之外的手机
   */
  getUserPhoneTypeFlg: function () {
    var phoneType = '';
    if (this.data.systemInfo && this.data.systemInfo.brand) {
      phoneType = this.data.systemInfo.brand + this.data.systemInfo.model + "";
    } else {
      let systemInfo = wx.getStorageSync('systeminfo');
      phoneType = systemInfo.brand + systemInfo.model + "";
    }
    phoneType = phoneType.toLowerCase();
    if (phoneType.indexOf('huawei') != -1) {
      return false;
    } else if (phoneType.indexOf('oppo') != -1) {
      return false;
    } else if (phoneType.indexOf('xiaomi') != -1) {
      return false;
    } else if (phoneType.indexOf('iphone') != -1) {
      return false;
    } else if (phoneType.indexOf('vivo') != -1) {
      return false;
    } else {
      return true;
    }
  },

  /**
   * 跳转到如何打开定位页面
   */
  toBlueTip(e) {
    console.log('toBlueTip', e);
    let type = e.currentTarget.dataset.type;
    if (this.data.systemInfo) {
      var phoneType = this.data.systemInfo.brand + this.data.systemInfo.model;
      var system = this.data.systemInfo.system;
    } else {
      let systemInfo = wx.getStorageSync('systeminfo');
      var phoneType = systemInfo.brand + systemInfo.model;
      var system = systemInfo.system;
    }
    wx.navigateTo({
      url: 'blue_tip/blue_tip?phoneType=' + phoneType.toLowerCase() + '&type=' + type + '&system=' + system.toLowerCase(),
    })
  },

  /**
   * 监听网络状态
   */
  getNetwork: function () {
    var that = this;
    wx.getNetworkType({
      success: function (res) {
        // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
        that.data.networkType = res.networkType
      }
    })
    wx.onNetworkStatusChange(function (res) {
      console.log('networkType-------->', res)
      let networkType = res.networkType
      let isConnected = res.isConnected
      app.globalData.networkIsCon = isConnected
      if (!isConnected && app.globalData._that) {
        if (typeof app.globalData._that.networkFail == 'function') {
          app.globalData._that.networkFail()
        }
      }
      that.setData({
        networkType: networkType,
        isConnected: isConnected,
        networkFailDesc: !isConnected ? '网络已断开，请检查网络后再进行使用' : ''
      })
    })
  },

  /**
   * 获取地图上要展示的组件信息
   */
  getShowControlsInfo: function () {
    var that = this
    //set the width and height
    // 动态设置map的宽和高
    console.log("getSystemInfo--start")
    wx.getSystemInfo({
      success: function (res) {
        console.log("getSystemInfo--success", res)
        wx.setStorage({
          key: 'systeminfo',
          data: res,
        })
        let phoneNoDirFlg = that.getUserPhoneTypeFlg();
        that.setData({
          phoneInfo: res.brand + '-' + res.model + '-' + res.system,
          phoneNoDirFlg: phoneNoDirFlg
        })
        var verArr = res.version.split(".");
        var sys = res.system.toLowerCase();
        var flg = false
        if (verArr[0] < 6) {
          flg = true
        } else if (verArr[0] == 6) {
          if (verArr[1] < 5) {
            flg = true
          } else if (verArr[1] == 5) {
            if (verArr[2] < 11) {
              flg = true
            }
          }
        }

        var sysFlg = false
        if (sys.indexOf("android") != -1) {
          sys = sys.replace("android", "").trim()
          var sysVerArr = sys.split(".")
          //低于4.4.2的给予提示
          var limitVer = "4.4.2"
          var limitVerArr = limitVer.split(".");
          let sysFirst = parseInt(sysVerArr[0]);
          if (sysFirst < limitVerArr[0]) {
            sysFlg = true
          } else if (sysFirst == limitVerArr[0]) {
            let sysSecond = parseInt(sysVerArr[1]);
            if (sysSecond < limitVerArr[1]) {
              sysFlg = true
            } else if (sysSecond == limitVerArr[1]) {
              let sysThird = parseInt(sysVerArr[2]);
              if (sysThird < limitVerArr[2]) {
                sysFlg = true
              }
            }
          }
        }
        if (sysFlg) {
          that.setData({
            mapShowStatus: false,
            tipStatus: true,
            tipContent: "安卓系统低于" + limitVer + ",可能无法完成租赁"
          })
        } else if (flg) { //6.5.11
          that.setData({
            mapShowStatus: false,
            tipStatus: true,
            tipContent: "微信版本低,请升级微信后租赁"
          })
        }

        that.data.systemInfo = res
        console.log("that.data.systemInfo", that.data.systemInfo)

      },
      fail: function (res) {
        console.log("getSystemInfo--fail", res)
      }
    });

  },
  /**
   * 检测用户是否登录，或进行口令更新
   */
  checkUserSession: function () {
    var that = this
    wx.checkSession({
      success: function () {
        console.log('checkSession success,loginHandle', that.data.isSlide)
        if (that.data.isSlide == 1) {
          that.getApageLeaseRecord(1)
        }
        loginHandle(that, true);
      },
      fail: function () {
        //登录态过期
        that.loginAuth('', '');
      }
    });
  },
  location: function () {
    var that = this;
    that.showHelpLocationSet()
  },
  /**
   * 点击扫码时检查是否微信授权操作 暂未启用
   */
  scanAuthCheck: function () {
    var that = this;
    that.scan();
  },
  //扫码还
  scanBack: function () {
    this.scan(true);
  },
  //扫码租赁
  scan: function (isScanBack) {
    if (!app.globalData.networkIsCon) {
      wx.showToast({
        title: '请先打开网络',
      })
      return
    }

    var that = this
    //隐藏可以关不蓝牙
    that.data.hideIsDisconnectStat = true;
    that.data.isRetry85 = true;

    app.globalData.isConnecting = false;
    //是否租赁连接而不是升级连接，true租赁连接，false升级连接
    app.globalData.isLeaseCon = true;
    //初始化要升级的mac信息
    app.globalData.upgradeMac = '';

    that.data.cur_act = 'scan'

    //获取定位
    common.locationAddr(function (res) {
      that.data.locationLng = res.longitude;
      that.data.locationLat = res.latitude;
      that.data.locationTime = new Date().getTime();
    });

    var nophone = app.getUserLoginNoPhone();
    if (isScanBack === true) {
      this.data.isScanBack = true;
      //扫码还的操作不校验登录
      nophone = 2;
    } else {
      this.data.isScanBack = false;
    }
    if (nophone == null || nophone == undefined || nophone == 1) {
      this.setData({
        phoneAuthStatus: true,
        phoneAuthBtt: 'scan'
      });
      // return;
    } else if (nophone == 2) {
      this.setData({
        phoneAuthStatus: false,
        phoneAuthBtt: ''
      });
    }

    //特殊机型蓝牙连接超时时间设置
    if (this.data.systemInfo) {
      var systemInfo = this.data.systemInfo
      var phoneType = systemInfo.model
      if (systemInfo.system) {
        var sys = systemInfo.system.toLowerCase()
        var version = systemInfo.version

        if (sys.indexOf("android") != -1 && version == "6.0.1" && isSpecialPhone(phoneType, this)) {
          //特殊机型设置超时时长
          BLELocker.setConnectiTimeOut(15)
        }
      }
    }

    if (that.data.scanningCode) {
      wx.showToast({
        title: '请稍候',
        icon: 'none',
      })
      that.setData({
        loading_show: true,
        loading_desc: '处理中...',
        connectDesc: "处理中...",
      });
      setTimeout(function () {
        if (that.data.loading_desc == '处理中...') {
          that.data.scanningCode = false;
          that.setData({
            openning_show: false,
            loading_show: false,
            modal: {
              modal_show: true,
              desc_mini: "扫码无反应",
              desc: "请重试扫码",
              retryConnect: true
            }
          });
        }
      }, 3000);
      return;
    }
    that.data.scanningCode = true;
    common.storeWxClientType(that);

    //清空通过微信扫一扫进入得到的二维码内容
    app.globalData.wxScan.qrc = '';

    wx.scanCode({
      onlyFromCamera: true,
      success: (res) => {
        that.data.isWxScanFlg = false;
        var qrc = '';
        var qrCode = res.result;
        if (!qrCode) {
          that.setData({
            loading_show: false,
            alertBoxStatus: true,
            alertBoxTipContent: '二维码为空,请重新扫码',
            qrcContent: ''
          })
          that.recordBlueConnectError(ConstantData.err_type.qrc_null, "二维码为空,qrc=" + qrCode)
          that.data.scanningCode = false;
          return;
        }
        let macReg = /[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}/;
        let isMacAddr = macReg.test(qrCode);
        if (qrCode.indexOf(ConstantData.CONSTATNT_DATA.DEVICE_QRCODE_URL_PREFIX) == 0 || isMacAddr) {
          //设备二维码
          let qrc_old = app.getScanQrcContent();
          that.data.qrcContent = qrCode;
          if (isMacAddr) {
            qrc = qrCode.replace(/:/g, "");
          } else {
            var rst = qrCode.split('/');
            qrc = rst[rst.length - 1];
            console.log("------>>-------->>qrc_old", qrc_old)
            console.log("------>>-------->>qrc", qrc);
            that.data.qrc = qrc;
          }

          app.globalData.scan.qrc = qrc;
          try {
            wx.setStorageSync('scan_qrc', qrc);
          } catch (e) {}
          if (qrc != qrc_old) {
            wx.removeStorageSync('blue_fail_time')
            wx.removeStorageSync('rfid_error_time')
            wx.removeStorageSync('insert_fail_time')
            wx.removeStorageSync('hook_fail_time')
            wx.removeStorageSync('has_opened_gprs')
            wx.removeStorageSync('no_eject_times')
            this.setData({
              isReturn: 0
            })
          }
        } else if (qrCode.indexOf(ConstantData.CONSTATNT_DATA.TIME_CARD_QRCODE_URL_PREFIX) == 0) {
          //包时卡二维码地址
          console.log("time card------------------------>handle")
          //检测包时卡是否付款，是否绑定
          var cardNumber = qrCode.substring(ConstantData.CONSTATNT_DATA.TIME_CARD_QRCODE_URL_PREFIX.length)
          console.log("scan-----------cardNumber=" + cardNumber)
          app.toTimeCardDetail(cardNumber)
          that.data.scanningCode = false;
          return
        } else if (qrCode.indexOf(ConstantData.CONSTATNT_DATA.TIME_CARD_CHAINLOCK_QRCODE_URL_PREFIX) == 0) {
          //包时卡二维码地址
          console.log(res.result, "time card------------------------>handle")
          that.data.strPath = res.result;
          console.log(that.data.strPath.indexOf('?') != -1, '我是测试1111')
          if (that.data.strPath.indexOf('?') != -1) {
            var urlArr = that.data.strPath.split('?');
            var strPath = urlArr[0].split('/')
            that.data.typestr = strPath[strPath.length - 1];
            var paramsArr = urlArr[1].split('&')
            console.log(paramsArr, '我是测试444')
            that.data.orderCode = paramsArr[0].split("=")[1];
          } else {
            var urlArr = that.data.strPath.split('/')
            var strPath = urlArr[urlArr.length - 1]
            that.data.typestr = strPath;
            that.data.orderCode = "";
          }

          console.log(that.data.orderCode, 'res___orderCode')
          console.log(that.data.typestr, "time card------------------------>handle")
          // //检测包时卡是否付款，是否绑定
          // var cardNumber = qrCode.substring(ConstantData.CONSTATNT_DATA.TIME_CARD_CHAINLOCK_QRCODE_URL_PREFIX.length)
          wx.reLaunch({
            url: '../interlayer/interlayer?card=' + that.data.typestr + '&order=' + that.data.orderCode,
          })
          return
        } else if (qrCode.indexOf(ConstantData.CONSTATNT_DATA.TO_DEPOSIT_VIEW_URL) == 0) {
          that.data.scanningCode = false;
          //跳转到押金页面
          wx.navigateTo({
            url: '../user_record/deposit/user_deposit',
          })
          return
        } else {
          that.setData({
            loading_show: false,
            codeError: true,
            alertBoxTipContent: '二维码有误!',
            qrcContent: ''
          })

          that.data.scanningCode = false;
          that.recordBlueConnectError(ConstantData.err_type.qrc_err, "二维码有误,qrc=" + qrCode)
          return
        }

        that.setData({
          selBindUserId: 0,
          bindUserList: [],
          selBindUser: {},
          cancelAgentSelLeaseStatus: true
        })

        var nophone = app.getUserLoginNoPhone();
        if (nophone == null || nophone == undefined || nophone == 1) {
          try {
            wx.setStorageSync('scan_qrc', qrc);
          } catch (e) {}
          that.setData({
            phoneAuthStatus: true,
            phoneAuthBtt: 'scan',
            loading_show: false
          });

          that.data.scanningCode = false;

        }

        console.log("scan-----------qrc=" + qrc)
        console.log("******获取要连接的设备名称", app.globalData.conTimeoutTimer, !null);

        that.getDevIdAndConnect(qrc, 'scan');

      },
      fail: function (res) {
        that.data.scanningCode = false;
        that.setData({
          loading_show: false
        })
        that.data.qrcContent = '';
        that.recordBlueConnectError(ConstantData.err_type.qrc_cancel, "调用微信扫码失败或取消")
      }
    });

  },
  mine_center: function () {
    wx.navigateTo({
      url: '../user_center/user_center',
    })
  },
  /**
   * 去爱心租赁建立关系页面
   */
  outpatientCareLease: function (e) {
    let that = this;
    that.closeOtherPopup()
    var nophone = app.getUserLoginNoPhone();
    console.log("开始跳转到爱心租赁添加雇主页面")
    if (nophone == 1 || nophone == null || nophone == undefined) {
      that.setData({
        phoneAuthStatus: true,
        phoneAuthBtt: 'outpatient_add_employer',
        loading_show: false
      });
      that.toWxLogin();
      // wx.showToast({
      //   title: '请先登录',
      //   icon: 'none'
      // })
      return
    }
    wx.navigateTo({
      url: '../../pkgBak/pages/outpatient_service/manage_employer/manage_employer?isManage='+e,
    })
  },
  /**统计信息 */
  toVisitStatisticInfo: function () {
    let that = this;
    that.closeOtherPopup()
    var nophone = app.getUserLoginNoPhone();
    if (nophone == 1 || nophone == null || nophone == undefined) {
      that.setData({
        phoneAuthStatus: true,
        phoneAuthBtt: 'manager_hospitallist',
        loading_show: false
      });
      that.toWxLogin();
      // wx.showToast({
      //   title: '请先登录',
      //   icon: 'none'
      // })
      return;
    }
    wx.navigateTo({
      url: '../../pkgBak/pages/manager/hospitallist/hospitallist',
    })
  },
  /**
   * 共享电源管理人员
   */
  toAdminPowerUser: function () {
    let that = this;
    var nophone = app.getUserLoginNoPhone();
    console.log("开始跳转到爱心租赁添加雇主页面")
    if (nophone == 1 || nophone == null || nophone == undefined) {
      that.setData({
        phoneAuthStatus: true,
        phoneAuthBtt: 'outpatient_manage_careworker',
        loading_show: false
      });
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return;
    }
    wx.navigateTo({
      url: '../hospital_admin/power/power_admin/power_admin',
    })
  },
  /**现场操作人员处理 */
  toVisitOptAdminInfo: function () {
    let that = this;
    that.closeOtherPopup()
    var nophone = app.getUserLoginNoPhone();
    if (nophone == 1 || nophone == null || nophone == undefined) {
      that.setData({
        phoneAuthStatus: true,
        phoneAuthBtt: 'opt_user_admin_menus',
        loading_show: false
      });
      that.toWxLogin();
      // wx.showToast({
      //   title: '请先登录',
      //   icon: 'none'
      // })
      return;
    }
    wx.navigateTo({
      url: '../../pkgBak/pages/opt_user_admin/menus/menus',
    })
  },
  /**
   * 获取用户的短信码
   */
  messageUserPhone: function () {
    let that = this;
    var nophone = app.getUserLoginNoPhone();
    if (nophone == 1 || nophone == null || nophone == undefined) {
      that.setData({
        phoneAuthStatus: true,
        phoneAuthBtt: 'user_phone_code',
        loading_show: false
      });
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return;
    }
    wx.navigateTo({
      url: '../../pkgBak/pages/help/user_phone_coce/user_phone_code',
    })
  },
  /**
   * 门诊租赁管理
   */
  outpatientCareManage: function () {
    let that = this;
    that.closeOtherPopup()
    var nophone = app.getUserLoginNoPhone();
    console.log("开始跳转到爱心租赁添加雇主页面")
    if (nophone == 1 || nophone == null || nophone == undefined) {
      that.setData({
        phoneAuthStatus: true,
        phoneAuthBtt: 'outpatient_manage_careworker',
        loading_show: false
      });
      that.toWxLogin();
      // wx.showToast({
      //   title: '请先登录',
      //   icon: 'none'
      // })
      return;
    }
    wx.navigateTo({
      url: '../../pkgBak/pages/outpatient_service/manage_careworker/manage_careworker',
    })
  },
  /**
   * 去预约轮椅
   */
  toSubscribeEqu: function () {
    this.closeOtherPopup()
    if (this.data.subEquCount > 0) {
      wx.navigateTo({
        url: '../user_record/lease/user_lease',
      })
    } else {
      wx.navigateTo({
        url: '../../pkgBak/pages/sub_scenes/sub_scenes',
      })
    }
  },

  //蓝牙适配器状态
  getBLEStatus: function () {
    wx.getBluetoothAdapterState({
      success: function (res) {
        console.log(res)
      }
    })
  },

  /**
   * 地图定位设置帮助
   */
  showHelpLocationSet: function () {
    var locationHelpImg = this.data.phoneSetLocationHelpImg
    if (!locationHelpImg) {
      wx.navigateTo({
        url: '../more/about/about',
      })

      return
    }
    wx.navigateTo({
      url: '../../pkgBak/pages/help/system_set/phone_location_set?imgs=' + locationHelpImg,
    })
  },

  showRule: function (ruleInfo) {
    this.setData({
      connectType: '租借'
    })
    this.setData({
      showModalStatus: true,
      mapShowStatus: false,
      loading_show: false,
      bindUserListStatus: false,
      agentLeaseSelStatus: false
    });
  },
  positionHoming: function (lat, lng) {
    var that = this;
    var markers = [];
    var businessName = {};
    var equIcon = "../../image/wheelchair.png";

    app.executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/nearby/eqts',
        method: 'post',
        header: header,
        data: {
          lat: lat,
          lng: lng
        },
        success: function (data) {
          let netErr = app.handleRes(data, that);
          if (netErr) {
            return
          }
          var data = data.data;
          for (var i = 0; i < data.length; i++) {
            var lat = data[i].lat;
            var lng = data[i].lng;
            var bid = data[i].bid;
            var title = data[i].businessName;

            var temp = {
              id: bid,
              iconPath: equIcon,
              longitude: lng,
              latitude: lat,
              width: 48,
              height: 50
            }
            markers[i] = temp;
            businessName[bid] = title;
          }

          that.setData({
            markers: markers
          });
          app.businessName = businessName;
        }
      })
    })

  },
  getDevIdAndConnect: function (qrc, type) {   
    //验证登录
    if(this.data.isScanBack == true) {
      var nophone = app.getUserLoginNoPhone();
      if (nophone == null || nophone == undefined || nophone == 1) {
        this.toWxLogin()
        return
      }
    }    
    this.data.scanningCode = false
    this.setData({
      loading_show: false,
      isSlide:1
    })
    common.clearConTimeCountTimer('1488');
    wx.navigateTo({
      url: '/pkgNew/pages/newConnectDev/index?qrc=' + escape(qrc) + '&type=' + type + '&depositAutoBack=' + this.data.depositAutoBack +
        '&isScanBack=' + this.data.isScanBack +
        '&wxScore=' + this.data.wxScore +
        '&connectType=' + this.data.connectType,
    })   
  },
  /**
   * 处理扫码从服务获取设备信息
   */
  handleConDevRes: function () {
    let that = this
    let res = that.data.conDevRes
    console.log("处理扫码获取的设备信息:", res)
    if (res.data.extParams && res.data.extParams.lockType) {
      that.setData({
        lockType: res.data.extParams.lockType
      })
    }
    that.recordBlueConnectError(ConstantData.err_type.qrc_mac_suc, 'getDevIdAndConnect macId=' + (res.data ? res.data.macId : 'null'));
    //扫码后获取到的连接的mac地址
    that.data.conMac = res.data ? res.data.macId : "";
    that.data.conBlueName = res.data ? res.data.extParams.blueName : "";
    app.globalData.conBlueVer = res.data ? res.data.extParams.blueVer : "";
    that.startConnect(res);
  },
  //开始进行蓝牙连接
  startConnect: function (res) {
    var that = this;
    //取消重试
    let netErr = app.handleRes(res, that);
    if (netErr) {
      that.data.scanningCode = false;
      that.setData({
        loading_show: false
      })
      return
    }
    if (res.data.isBindPhone == 0) {
      that.setData({
        phoneAuthStatus: true,
        phoneAuthBtt: 'scan',
        loading_show: false
      });
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      that.data.scanningCode = false;
      return;
    }
    that.setData({
      phoneAuthStatus: false,
      phoneAuthBtt: ''
    });
    app.globalData.curConHid = null;
    if (res.data.hid) {
      that.setData({
        pile_id: res.data.hid
      })
      app.globalData.curConHid = res.data.hid;
      wx.setStorageSync('pileId', res.data.hid);
      that.data.pile_type = res.data.hpVer && res.data.hpVer.indexOf('长') != -1;
    }
    app.globalData.isLeaseCon = false;
    app.globalData.isAllowUpgrade = false;
    app.globalData.isBeforeLeaseUpgrade = false;
    app.globalData.allowUpgradeOtherMac = false;
    app.globalData.isPayUpgrade = false;
    app.globalData.isLockUpgrade = false;
    app.globalData.otherMacs = [];
    that.data.isFirstUseNewConLeaseFlg = false;
    that.data.isSend98Cmd = false;
    that.data.canRetry85 = false;

    if (res.data.extParams) {
      that.data.conDevExtParams = res.data.extParams;
      app.globalData.isAllowUpgrade = res.data.extParams.isAllowUpgrade;
      app.globalData.lastDriveVer = res.data.extParams.lastDriveVer;
      app.globalData.isBeforeLeaseUpgrade = res.data.extParams.isBeforeLeaseUpgrade;
      app.globalData.isPayUpgrade = res.data.extParams.isPayUpgrade;
      app.globalData.isLockUpgrade = res.data.extParams.isLockUpgrade;
      app.globalData.allowUpgradeOtherMac = res.data.extParams.allowUpgradeOtherMac ? res.data.extParams.allowUpgradeOtherMac : false;
      app.globalData.otherMacs = res.data.extParams.otherMacs ? res.data.extParams.otherMacs : [];
      //是否第一次是用新的蓝牙连接方式
      that.data.isFirstUseNewConLeaseFlg = res.data.extParams.isFirstUseNewConLeaseFlg ? res.data.extParams.isFirstUseNewConLeaseFlg : false;
      //是否发送98命令
      that.data.isSend98Cmd = res.data.extParams.isSend98Cmd ? res.data.extParams.isSend98Cmd : false;
      //网关连接超时的时长。默认20秒超时
      app.globalData.gatewayConTimeout = res.data.extParams.gatewayConTimeout ? res.data.extParams.gatewayConTimeout : 20000;
      //网关开锁超时的时长,默认15秒超时
      app.globalData.gatewayUnlockTimeout = res.data.extParams.gatewayUnlockTimeout ? res.data.extParams.gatewayUnlockTimeout : 15000;
      //网关连接失败后多长时间内使用蓝牙重试连接，默认为5分钟内再次扫码可使用蓝牙连接
      app.globalData.gatewayFailBleConTime = res.data.extParams.gatewayFailBleConTime ? res.data.extParams.gatewayFailBleConTime : 30000;
      //蓝牙连接失败后多长时间内使用网关重试连接，默认为5分钟内再次扫码可使用网关连接
      app.globalData.gatewayBleFailConTime = res.data.extParams.gatewayBleFailConTime ? res.data.extParams.gatewayBleFailConTime : 30000;
    }



    //清空定时器
    app.clearTimeoutTimer();
    //清空秘钥
    that.data.blepwd = '';

    app.globalData.startConTime = new Date().getTime();

    that.data.newConFlg = res.data.newConFlg;

    let version = wx.getSystemInfoSync().SDKVersion;
    let miniFileIsOk = common.compareVersion(version, ConstantData.CONSTATNT_DATA.FILE_SYSTEM_MANAGER_MIN_SDK_VER) >= 0;
    console.log("文件系统文件接口是否可用>", miniFileIsOk, app.globalData.allowUpgradeOtherMac);
    if (app.globalData.isBeforeLeaseUpgrade && miniFileIsOk) {
      //升级的操作不允许进行连接的操作
      app.globalData.isLeaseCon = false;
      that.setData({
        loading_show: false
      })
      wx.showLoading({
        title: '更新中..',
        mask: true
      });

      //租赁前先进行升级，然后重新扫码进行租赁
      common.recordErrorInfo(ConstantData.CONSTATNT_DATA.LOG_TYPE_BEFORE_LEASE_UPGRADE_START, "开始升级:" + "DK" + res.data.macId);
      console.log("开始升级驱动文件。。。");
      //非陪护床的控制盒可以走静默升级,只做升级不处理其他业务
      app.globalData.upgradeScanMacRes = res;
      //扫码获取的mac
      var mac = "DK" + res.data.macId;
      app.globalData.upgradeMac = mac;
      downloadUtil.downloadZip().then(() => {
        console.log("开始扫描设备信息-->", mac)
        downloadUtil.unzipFile();
        connectUtil.scanDevice(mac);
        wx.showLoading({
          title: '扫描..',
          mask: true
        });
      }, (res) => {
        console.error("下载失败---->", res, mac)
        common.recordErrorInfo(ConstantData.CONSTATNT_DATA.LOG_TYPE_BEFORE_LEASE_UPGRADE_START, "下载失败:" + mac);
      });
      setTimeout(function () {
        getApp().hideLoading();
      }, 120000);
    } else {
      //连接的调用不允许进行升级的操作
      app.globalData.isBeforeLeaseUpgrade = false;
      app.globalData.isLeaseCon = true;
      //扫完码拿到数据执行连接的过程
      that.executeConnect(res);
    }

  },
  //执行蓝牙连接
  executeConnect: function (res) {
    var that = this;
    //清空选择的设备类型
    that.setData({
      selTypeList: [],
    })
    //连接前去除95重试标记
    that.data.retry95Flg = false;
    let pile_id = that.data.pile_id ? 'Z' + that.data.pile_id : '';
    let errType = '';
    let user_no_back = wx.getStorageSync('user_no_back');
    if (res.data.rst == 0 || (res.data.rst == 6 && user_no_back)) {

      var hpStat = res.data.hpStat;
      if (hpStat && hpStat != 0 && hpStat != 1) {
        // var desc = res.data.desc ? res.data.desc : "维护中,请使用其他设备";
        if (user_no_back) {
          errType = ConstantData.err_type.qrc_maintain_back;
          var desc = "归位桩维护中,如您确定设备已锁在桩上拉不下来,请联系客服处理";
          var desc_mini = "桩维护" + pile_id + "(" + that.data.phoneInfo + "-" + errType + ")";
          var contact = true;
          var confirm = false;
        } else {
          errType = ConstantData.err_type.qrc_maintain_rent;
          var desc = res.data.desc ? res.data.desc : "归位桩维护中,请换其它桩租赁";
          var desc_mini = "桩维护" + pile_id + "(" + that.data.phoneInfo + "-" + errType + ")";
          var contact = false
          var confirm = true
        }
        //归位桩存在问题
        that.setData({
          loading_show: false,
          modal: {
            modal_show: true,
            desc: desc,
            desc_mini: desc_mini,
            open_location_show: false,
            retryConnect: false,
            retry95: false,
            confirm: confirm,
            contact: contact
          }
        })
        that.recordBlueConnectError(errType, 'modalErr:归还失败');
        that.data.scanningCode = false;
        return;
      }

      BLELocker.setHomingDeviceServiceInfo(res.data.homing_uuid, res.data.homing_FEC7, res.data.homing_FEC8, res.data.homing_FEC9)

      var name = res.data.macId;
      if (name == null || name == '') {
        console.log("根据qrc获取mac名称为空")
        errType = ConstantData.err_type.qrc_mac_null;
        that.setData({
          loading_show: false,
          modal: {
            modal_show: true,
            desc: '请重新扫码-' + errType,
            confirm: true
          }
        })
        that.recordBlueConnectError(errType, 'modalErr:获取mac为空');
        that.data.scanningCode = false;
        return
      }
      var deviceId = res.data.deviceId

      let isExtBlueName = that.data.conBlueName && that.data.conBlueName.indexOf("DK") == -1;
      let conBlueName = isExtBlueName ? that.data.conBlueName : "DK" + name;
      that.setData({
        loading_show: true,
        loading_desc: '开始连接...',
        agentLeaseSelStatus: false,
        showModalStatus: false,
        wxDeviceId: deviceId, //数据库存储的公众号获取的设备id
        curBlueName: conBlueName,
        isNoRfidOpen: res.data.isNoRfidOpen,
        isJudgeInsertSwitch: res.data.judgeInsertSwitch,
        isBackChairStatus: res.data.backStat,
        curIsDirectCon: res.data.curIsDirectCon
      })

      setTimeout(function () {
        that.data.scanningCode = false;
      }, 1000);

      app.globalData.isAllowBroadcastBack = res.data.isAllowBroadcastBack;

      //TEST CODE
      // that.recordBlueConnectError(1,"搜索失败")

      //发起蓝牙连接
      var logData = {
        reqNumber: 3,
        optDesc: "发起蓝牙连接请求" + that.data.qrc + ",mac:DK" + name
      };
      that.connectLog(logData)

      //蓝牙集群节点判断处理
      //是否存在蓝牙节点
      var colonyIsExists = res.data.colonyIsExists;
      //集群节点是否在使用中0未占用,1被占用
      var colonyIsUsing = res.data.colonyIsUsing;
      //是否直接使用蓝牙节点连接
      var hpIsColony = res.data.hpIsColony;
      that.data.hpIsColony = hpIsColony;
      //是否可直接使用节点
      var colonyIsDirectUse = hpIsColony == 1 && colonyIsUsing == 0 && colonyIsExists == 1;

      console.log("是否直接网关连接:", colonyIsDirectUse);

      let firstConFail = colonyBlue.isBleFailGatewayCon();
      console.log("是否首次蓝牙连接失败:", firstConFail);
      //是否在连接失败后使用
      var colonyIsFailUse = hpIsColony == 2 && colonyIsUsing == 0 && colonyIsExists == 1;
      if (colonyIsFailUse && firstConFail) {
        colonyIsDirectUse = true;
        that.setData({
          colonyConFail: 0
        })
      }

      that.data.noBackEqId = res.data.extParams.noBackEqId;
      //网关连接失败后5分钟内扫码，改用蓝牙连接
      let isBleCon = colonyBlue.isGatewayFailBleCon();
      console.log("是否首次网关连接失败:", isBleCon);
      if (!isBleCon && colonyIsDirectUse && that.data.colonyConFail < 3) {
        //开锁前判断是否是蓝牙集群的连接
        that.data.mac = name
        that.data.colonyIsExists = colonyIsExists
        common.storeGatewayClientType();
        console.log("开始直接连接蓝牙集群---->");
        //直接使用蓝牙集群连接
        colonyBlue.connectDev(name, that);
        return;
      }


      if (that.data.pt == 'blue_tip') {
        that.data.pt = '';
      }

      //非网关的使用wxmini
      common.storeWxClientType(that);
      //进行蓝牙连接
      that.data.timeout95RetryFlg = true; //连接后95超时可以进行一次重连
      that.data.retryCon = false; //刚开始还没有进行重试点击
      that.recordBlueConnectError(ConstantData.err_type.qrc_start_connect, '获取mac成功，开始连接');
      that.connectBLEDevice(conBlueName);
    } else if (res.data.rst == 6) { //共享陪护床
      that.setData({
        modal: {
          modal_show: true,
          desc: that.data.conDevExtParams && that.data.conDevExtParams.close_tip ? that.data.conDevExtParams.close_tip : "当前时间不可租借",
          confirm: true
        }
      })
      that.data.scanningCode = false;
    } else {
      errType = ConstantData.err_type.qrc_mac_rst;
      that.setData({
        modal: {
          modal_show: true,
          desc: '请重新扫码-' + errType,
          confirm: true
        }
      })
      that.data.scanningCode = false;
      console.log("根据qrc获取mac请求返回值非0：" + res.data.rst)
      that.recordBlueConnectError(errType, 'modalErr--qrc=' + that.data.qrc + '--' + res.data.rst);
    }

  },
  //记录归位桩蓝牙连接错误日志
  recordBlueConnectError: function (errType, errDesc, tag) {
    var that = this


    let nowTime = util.formatTime(new Date()) + '-----';

    console.log("记录错误日志到服务器...", that.data.curBlueName, that.data.systemInfo.system, errType, nowTime + errDesc);
    const sysInfo = wx.getSystemInfoSync()
    let authStr = sysInfo ? (sysInfo.locationAuthorized + ',' + sysInfo.bluetoothEnabled + ',' + sysInfo.locationEnabled + ',' + sysInfo.wifiEnabled) : 'null'
    var miniVer = ConstantData.CONSTATNT_DATA.MINI_VERSION
    app.executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/error/bc',
        method: 'post',
        header: header,
        data: {
          homingPileBlueName: that.data.curBlueName, //归位桩的蓝牙名称,最长100个字
          phoneOs: that.data.systemInfo.system, //手机系统信息,最长245
          phoneFactory: that.data.systemInfo.model, //手机厂商,最长245
          phoneType: that.data.systemInfo.model || that.data.systemInfo.brand, //手机型号,最长245
          weixinVer: that.data.systemInfo.version + ',' + that.data.systemInfo.SDKVersion + ',' + miniVer, //微信版本号,最长45
          errType: parseInt((errType + '').replace(/[^0-9]/ig, '')), //错误类型,最大值127；1.搜索,2.连接,3.auth,4.init 5. 95 6. 85
          errDesc: nowTime + '[' + authStr + ']' + ',' + errDesc + ',', //错误描述,最长545
          tag: tag && tag != 'undefined' ? tag : ''
        },
        success: function (res) {
          console.log("recordErrSuc", res)
          let netErr = app.handleRes(res, that);
          if (netErr) {
            return
          }
          // console.log("蓝牙连接错误日志记录成功", errDesc);
        },
        fail: function (res) {
          // console.log("蓝牙连接错误日志记录失败")
          console.log("recordErrFail", res)
        }
      })
    })


  },
  //记录归还蓝牙连接超时的日志
  recordReturnBlueTimeoutError: function (errType, errDesc) {

    var that = this
    var miniVer = ConstantData.CONSTATNT_DATA.MINI_VERSION
    app.executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/error/noreturn',
        method: 'post',
        header: header,
        data: {
          homingPileBlueName: that.data.curBlueName, //归位桩的蓝牙名称,最长100个字
          phoneOs: that.data.systemInfo.system, //手机系统信息,最长245
          phoneFactory: that.data.systemInfo.model, //手机厂商,最长245
          phoneType: that.data.systemInfo.model, //手机型号,最长245
          weixinVer: that.data.systemInfo.version + ',' + that.data.systemInfo.SDKVersion + ',' + miniVer, //微信版本号,最长45
          errType: errType, //错误类型,最大值127；1.搜索,2.连接,3.auth,4.init 5. 95 6. 85
          errDesc: errDesc, //错误描述,最长545
        },
        success: function (res) {
          let netErr = app.handleRes(res, that);
          if (netErr) {
            return
          }
          console.log("归还蓝牙连接超时日志记录成功")
          console.log(res)
        },
        fail: function (res) {
          console.log("归还蓝牙连接超时日志记录失败")
          console.log(res)
        }
      })
    })


  },
  //连接蓝牙设备
  connectBLEDevice: function (blueName) {
    getApp().hideLoading()
    var that = this;

    let isGatewayConFlg = colonyBlue.isGatewayCon(that);
    if (isGatewayConFlg) {
      console.log("开始网关连接", blueName)
      that.setData({
        loading_show: true,
        loading_desc: '网关连接准备中...',
        connectDesc: "网关连接准备中...",
      });
      colonyBlue.connectDev(blueName.replace("DK", ""), that);
      return;
    } else {
      //使用蓝牙连接检查蓝牙相关权限
      console.log("miniAuth:", app.globalData.miniAuthSetting)
      //第一使用蓝牙连接，检查蓝牙连接权限
      let isAuth = commonUtil.validateBleAuth()
      if (isAuth == 'sys_ble_ios') {
        wx.showModal({
          title: '提示',
          content: '连接设备需蓝牙权限,请打开系统蓝牙权限',
          success(res) {}
        })
        return
      } else if (isAuth == 'sys_ble_android') {
        //系统蓝牙未打开跳转到对应页面
        wx.showModal({
          title: '提示',
          content: '连接设备需蓝牙权限,点击"确定"按钮去打开系统蓝牙权限',
          success(res) {
            if (res.confirm) {
              wx.openSystemBluetoothSetting({
                success(res) {
                  console.log("打开系统蓝牙配置", res)
                }
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
        that.setData({
          loading_show: false
        })
        common.clearConTimeCountTimer('1713');
        return
      } else if (isAuth == 'sys_location') {
        //跳转到系统定位权限        
        that.setData({
          openning_show: false,
          loading_show: false,
          modal: {
            modal_show: true,
            desc_mini: '',
            desc: '连接设备需定位权限,请检查定位服务是否已打开',
            icon_name: 'icon-dingwei',
            desc_extra: '点击“打开定位方法”可查看图示指引',
            retryConnect: false,
            open_location_show: true,
          }
        });
        common.clearConTimeCountTimer('1713');
        return
      } else if (isAuth == 'wx_location' || isAuth == 'wx_ble') {
        wx.showModal({
          title: '提示',
          content: isAuth == 'wx_location' ? '连接设备需要去微信"权限管理"中打开定位权限' : '连接设备需要去微信"权限管理"中打开蓝牙权限',
          success(res) {
            if (res.confirm) {
              wx.openAppAuthorizeSetting({
                success(res) {
                  console.log(res)
                }
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
        that.setData({
          loading_show: false
        })
        common.clearConTimeCountTimer('1713');
        return
      } else if (isAuth == 'mini_ble') {
        commonUtil.toSetMiniAuthSetting() // mark: 去打开微信小程序蓝牙权限
        that.setData({
          loading_show: false
        })
        common.clearConTimeCountTimer('1713');
        return
      }
    }
    common.storeWxClientType(that);

    console.log("connecting...." + blueName)
    that.data.canceledConnect = false;
    that.setData({
      loading_show: true,
      loading_desc: '连接准备中...',
      connectDesc: "连接准备中...",
      startConTime: new Date().getTime(),
      mac: blueName.replace("DK", "")
    });

    //蓝牙连接中
    var logData = {
      reqNumber: 4,
      optDesc: "设备连接中,请稍后..."
    };
    this.connectLog(logData)


    BLELocker.setErrorCallback(function (errType, errDesc) {
      that.recordBlueConnectError(errType, errDesc)
    })
    BLELocker.setConnectLogCall(function (data) {
      //记录蓝牙连接记录
      that.connectLog(data)
    })

    var timebyte = null;
    var encryptval = null;

    //关闭心跳定时器
    if (that.data.bleHeartTimer) {
      clearInterval(that.data.bleHeartTimer);
      console.log("连接前关闭之前的心跳定时器");
    }
    app.globalData.conIsSuc = false;
    app.globalData.upgradeMac = blueName;
    app.globalData.startConTime = new Date().getTime();
    //是否开锁中
    app.globalData.isOpenLock = false;
    app.globalData.isUpgradeing = false;

    //连接中标记
    app.globalData.isConnecting = true;
    //当前连接的mac
    that.data.mac = blueName.replace('DK', '');
    //连接前清空上一次扫码的设备记录
    BLELocker.setDevice(null);
    that.data.blueName = blueName;

    //是否搜的onBluetoothDeviceFound响应超时
    app.globalData.isFindTimeout = false;

    if (that.data.isFirstUseNewConLeaseFlg) {
      console.log("使用新连接进行连接");
      //非直接连接
      app.globalData.isDirectConnect = false;
      app.globalData._that.data.openBlueAdapterFail = false;
      app.globalData.isLeaseCon = true;
      BLELocker.setParams(function (status, data) {
        that.handleStatus(status, data)
      }, that);
      connectUtil.startCon(blueName);
      let isWxScan = that.data.isWxScanFlg ? "wxScan" : "ejiaScan";
      if (that.data.canRetry85) {
        isWxScan = isWxScan + ':retry85Con';
      }
      that.recordBlueConnectError(ConstantData.err_type.new_con, 'new connect 1.0 start:' + isWxScan);
    } else if (that.data.newConFlg) {
      //使用新的连接
      app.globalData.isDirectConnect = false;
      BLELocker.newConnect(blueName, function (status, data) {
        that.handleStatus(status, data)
      }, 0, false, encryptval, timebyte, that);
    } else if (that.data.curIsDirectCon) {
      console.warn("蓝牙直连-----》")
      //使用直接连接
      app.globalData.isDirectConnect = true;
      that.recordBlueConnectError(40010, 'directConnect start');
      BLELocker.directConnect(blueName, function (status, data) {
        that.handleStatus(status, data)
      }, 0, false, encryptval, timebyte, that);
    } else {
      app.globalData.isDirectConnect = false;
      BLELocker.connect(blueName, function (status, data) {
        that.handleStatus(status, data)
      }, 0, false, encryptval, timebyte, that) //设置超时时间time,0使用默认的超时时间
    }

    //记录桩的服务信息
    BLELocker.setCollectionServiceData(function (uuid, fce7, fce8, fce9) {
      console.log('暂不记录状服务信息');
    })

  },

  cancelLease: function () {
    app.globalData.isConnecting = false;
    BLELocker.disconnect('index1624')
    this.setData({
      showModalStatus: false,
      bindUserListStatus: false,
      mapShowStatus: true,
      hospitalTipBox: false,
      toPayDeposit: false,
    })
  },

  //继续租赁
  continueLease: function () {
    if (this.data.toPayDeposit) {
      this.setData({
        callServiceBoxStatus: true,
        hospitalTipBox: false,
        toPayDeposit: false,
      })
    } else {
      this.setData({
        connectType: '租借'
      })
      this.setData({
        showModalStatus: true,
        bindUserListStatus: false,
        mapShowStatus: false,
        hospitalTipBox: false,
      })
    }
  },
  //去登录
  toLogin: function () {
    wx.navigateTo({
      url: '../login/login',
    })
  },
  toWxLogin: function () {
    wx.navigateTo({
      url: '../wx-login/wx-login',
    });
  },
  //开锁
  openLock: function (e) {
    var that = this

    if (!that.data.read) {
      wx.showToast({
        title: '请勾选我已阅读'
      })
      return
    }
    if (this.data.isAllowNoDeposit && !this.data.noDepositFail) {
      //允许免押
    } else if (!this.data.isPayDeposit) {
      //非免押且未支付押金,弹去支付押金的框
      //交押金租赁
      that.setData({
        callServiceBoxStatus: true,
        openLockLeaseOptStatus: true,

        showModalStatus: false,
        loading_show: false,
        bindUserListStatus: false,
        payDepositStat: false,
        agentLeaseSelStatus: false
      });
      return;
    }

    if (that.data.openLockLeaseOptStatus == false) {
      console.log("租赁中")
      return
    }
    that.setData({
      openning_show: true,
      openning_desc: '开始请求租赁...',
      showModalStatus: false,
      mapShowStatus: true,
      loading_show: false,
      openLockLeaseOptStatus: false,
      bindUserListStatus: false,
      payDepositStat: false
    })

    that.recordBlueConnectError(ConstantData.err_type.deposit_create_order, "用户点击租赁,开始请求租赁-" + that.data.rfId)

    //进行租赁
    that.leaseEquipment();

  },

  //开锁并租赁设备
  leaseEquipment: function (isRedirectOpenLock) {

    var that = this
    console.log("代租赁-----uid=" + that.data.selBindUserId)

    var systemInfo = wx.getStorageSync('systeminfo');
    console.log("----->systeInfo=", systemInfo);
    var isCouldNoDeposit = util.isCouldNoDeposit(systemInfo);
    console.log("----->isCouldNoDeposit=", isCouldNoDeposit, that.data.isAllowNoDeposit);

    app.executeRequest(function (header) {
      console.log('header', header);
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/equipment_order',
        method: 'post',
        header: header,
        data: {
          eqid: that.data.wxEqId,
          hid: that.data.wxHid,
          eqtid: that.data.wxEqTid,
          bindUid: that.data.selBindUserId,
          bindUserType: that.data.bindUserType,
          isOldReq: 'lease_order', //2019-07-23用于兼容之前版本订单不能进行隐藏
          miniNoDeposit: isCouldNoDeposit && that.data.isAllowNoDeposit && !that.data.noDepositFail, //系统支持免押并且可以用户可以免押并且用户没有取消免押
          isGateway: that.data.isColonyCon //是否为网关下单,true是，false否
        },
        success: function (res) {
          let netErr = app.handleRes(res, that);
          if (netErr) {
            that.setData({
              openning_show: false,
            })
            return
          }
          that.data.send85Time = new Date().getTime();
          console.log('---租赁请求成功:', res)
          that.recordBlueConnectError(ConstantData.err_type.deposit_created_order, "生成记录-" + that.data.rfId + ",rst=" + res.data.result)
          console.log("-1111--leaseRes=", res);
          that.setData({
            hasOrderFlg: true,
            openning_show: true,
            openLockLeaseOptStatus: true,
            equId: res.data.data ? res.data.data.equId : 0,
            opentime: res.data.data ? res.data.data.openTime : '',
            orderCode: res.data.data ? res.data.data.orderCode : '',
          })
          wx.setStorageSync('opentime', res.data.data ? res.data.data.openTime : '');
          wx.setStorageSync('equId', res.data.data ? res.data.data.equId : 0);
          console.log("---leaseRes=", res)
          var result = res.data.result;
          console.log("----leaseSuc--result=", result);
          if (result == 0) {

            if (res.data.err === "no_pay_deposit") {
              //未交押金
              that.setData({
                callServiceBoxStatus: true,
                openLockLeaseOptStatus: true,
                openning_show: false,
                showModalStatus: false,
                loading_show: false,
                bindUserListStatus: false,
                payDepositStat: false,
                agentLeaseSelStatus: false
              });
              return;
            }

            console.log("租赁成功");
            if (isRedirectOpenLock === true) {
              console.log("租赁成功,直接开锁");
              that.setData({
                openning_desc: '订单生成,准备开锁...',
              })
              that.recordBlueConnectError(ConstantData.err_type.deposit_pay_success_send85, "直接开锁-" + that.data.rfId);
              that.send85Command();
              return;
            }
            var backData = res.data.data;
            if (that.data.isAllowNoDeposit) {
              wx.setStorageSync("outOrderCode", backData.outOrderCode);
              if (!backData.no_deposit_info) {
                //免押创建订单失败,取消免押的订单，走押金支付
                noDepositLease.noSureCancelOrder(that);
                //免押失败使用交押金租赁
                that.setData({
                  callServiceBoxStatus: true,
                  openLockLeaseOptStatus: true,
                  openning_show: false,
                  showModalStatus: false,
                  loading_show: false,
                  bindUserListStatus: false,
                  payDepositStat: false,
                  agentLeaseSelStatus: false
                });
                return;
              }
              //免押跳转开锁中
              app.globalData.isOpenLock = true;
              //隐藏不断开蓝牙
              that.setData({
                hideIsDisconnectStat: false,
                noDepositBackFlg: false,
                openning_desc: '免押授权,页面跳转中(15秒)...',
                // openning_show: false,//冯慧敏 200114 跳转到免押页面前，就显示开锁中，以防止免押成功后用户点击扫码，影响开锁
              })
              that.recordBlueConnectError(ConstantData.err_type.deposit_to_auth, '免押授权,页面跳转中...')

              if (that.data.pt == 'noback') {
                //2019-07-25从使用中的页面扫码进行免押租赁的需要清除pt的标记值，以便免押流程进行
                that.data.pt = '';
              }

              that.data.noDepositCount = 15;
              app.globalData.noDepositTimer = setInterval(() => {
                that.data.noDepositCount = that.data.noDepositCount - 1;
                if (that.data.noDepositCount <= 0) {
                  clearTimeout(app.globalData.noDepositTimer);
                  that.setData({
                    openning_show: false,
                    callServiceBoxStatus: true,
                    hospitalTipBox: false,
                    toPayDeposit: false,

                    hideIsDisconnectStat: true,
                    noDepositBackFlg: true,
                  })
                } else {
                  that.setData({
                    openning_desc: '免押授权,页面跳转中(' + that.data.noDepositCount + '秒)...',
                  })
                }
              }, 1000)

              noDepositLease.toWxNoDepositLeasePage(backData.no_deposit_info, backData.outOrderCode, that);
            } else {
              that.send85Command();
            }
          } else {
            console.log("租赁失败")
            that.setData({
              openning_show: false,
            })
            if ('参数有误1' == res.data.description) {
              //存在未支付订单
              wx.showModal({
                title: '温馨提示',
                confirmText: "去支付",
                content: '存在未支付订单',
                success(res) {
                  if (res.confirm) {
                    // that.toPayOrder()//0717mark--直接吊起收银台
                    wx.navigateTo({
                      url: '../user_record/lease/user_lease',
                    })
                  } else if (res.cancel) {
                    console.log('用户点击取消')
                  }
                }
              })

              return;
            }

            if (result == 6000) {
              that.setData({
                alertBoxStatus: true,
                alertBoxTipContent: '如果确认再次租借'
              })
              return;
            }

            that.setData({
              alertBoxStatus: true,
              alertBoxTipContent: '租赁失败！' + result + 'Z' + that.data.wxHid
            })
          }
        },
        fail: function (res) {
          that.recordBlueConnectError(ConstantData.err_type.deposit_created_fail, "生成记录fail-" + that.data.rfId + ';res:' + JSON.stringify(res))

          console.log("租赁失败")
          console.log(res)
          that.setData({
            openning_show: false,
            alertBoxStatus: true,
            openLockLeaseOptStatus: true,
            alertBoxTipContent: '服务器忙,请重新扫码 Z' + that.data.wxHid
          })
        },
        complete: function () {}
      })
    })


  },
  // 支付订单
  toPayOrder: function (orderCode) {
    var that = this
    console.log("去支付。。。" + orderCode)
    app.toPayValideLogin(orderCode, function (loginCode, orderCode, err) {
      app.executeRequest(function (header) {

        wx.request({
          url: ConstantData.CONSTATNT_DATA.BASE_URL + '/ejiam/wxmini/weixin/pay',
          method: 'post',
          header: header,
          data: {
            orderCode: orderCode,
            loginCode: loginCode,
            wxErr: err
          },
          success: function (res) {
            var data = res.data
            console.log("支付结果---" + data.result)
            if (data.result != 0 || !data.data || !data.data.timeStamp) {
              console.log("租金支付失败----result=" + data.result + ",description=" + data.description)
              that.setData({
                modal: {
                  modal_show: true,
                  desc: data.description ? data.description : '支付失败',
                  confirm: true
                }
              })
              return
            }
            wx.requestPayment({
              appId: 'wx0e458dc331e557cc',
              timeStamp: data.data.timeStamp,
              nonceStr: data.data.nonceStr,
              package: data.data.package,
              signType: data.data.signType,
              paySign: data.data.paySign,
              success: function (res) {
                console.log("SUCCESS")
                console.log(res);
                // that.getSubscribeMessage('租金支付成功');
                wx.navigateTo({
                  url: '../user_record/lease/user_lease',
                })
              },
              fail: function (res) {
                common.recordErrorInfo(ConstantData.err_type.pay_fail, res ? 'index1-' + JSON.stringify(res) : '');
              },
              complete: function (res) {
                console.log("complete--" + data.data.paySign)
                console.log(res)
              }
            })
          },
          complete: function (res) {
            console.log("恢复支付。。。")
            that.setData({
              payStatus: true
            })
          }
        })

      })
    })

  },
  getSubscribeMessage: function (text, callback) {
    if (wx.requestSubscribeMessage) {
      console.log('【订阅消息】支持弹出订阅消息...')
      let tmplIds = ['KnUsFuS2NB07Pf9xbznQlyK_qZOU7DxOFl8l6E26Nww', '-S91jtVpX2Vto5EyXauKW008LYSSbsZiI8IWdepDarE'];
      let acceptIds = [];
      wx.requestSubscribeMessage({
        tmplIds: tmplIds,
        success(res) {
          console.log('【订阅消息】弹出订阅消息成功...' + JSON.stringify(res))
          let acceptIds = [];
          for (let i = 0; i < tmplIds.length; i++) {
            res[tmplIds[i]] == 'accept' ? acceptIds[i] = 1 : acceptIds[i] = 0;
          }
          app.executeRequest((header) => {
            wx.request({
              url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_user/wx_sub_msg',
              method: 'post',
              header: header,
              data: {
                acceptIds: JSON.stringify(acceptIds)
              }
            })
          })
        },
        fail(error) {
          console.log('【订阅消息】弹出订阅消息失败...' + JSON.stringify(error))
        },
        complete(res) {
          console.warn('【订阅消息】弹出订阅消息完成...' + text, res, acceptIds);
          if (callback) {
            callback();
          }
        }
      })
    } else {
      console.log('【订阅消息】不支持弹出订阅消息...')
      if (callback) {
        callback();
      }
    }
  },
  //关闭蓝牙适配器
  closeBLEAdapter: function () {
    wx.openBluetoothAdapter({
      success: function (res) {
        console.log(res)
      }
    })
  },
  /**
   * 关闭alertBox
   */
  alertBoxClose: function () {
    this.setData({
      alertBoxStatus: false,
      alertBoxTipContent: '',
      msgRst: 0,
      alertBoxBtnName: '确  定'
    })
  },
  /**
   * 点击确定
   */
  alertBoxBtnClick: function () {
    var that = this
    var msgVal = that.data.msgRst;
    console.log("sureBox----" + msgVal)
    console.log(this.data)
    that.setData({
      alertBoxStatus: false,
      alertBoxTipContent: '',
      msgRst: 0,
      alertBoxBtnName: '确  定'
    })
    if (msgVal == 1) {
      //归还成功
      wx.navigateTo({
        url: '../user_record/lease/user_lease?pt=backsuc&refundeqtid=' + that.data.refundEqTid + '&refundtip=' + that.data.refundTip + '&isRefundTip=' + that.data.isRefundTip
      })
    } else if (msgVal == 2) { //租赁记录去支付
      that.setData({
        alertBoxStatus: true,
        alertBoxTipContent: '请扫桩上二维码,完成归还!'
      })
    } else if (msgVal == 3) { //未交押金
      wx.setStorageSync("no_pay_deposit", 1);
      wx.navigateTo({
        url: '../deposit_list/deposit_list',
      })
    } else if (msgVal == 4) { //租赁记录去支付
      wx.navigateTo({
        url: '../user_record/lease/user_lease',
      })
    } else if (msgVal == 5) { //已缴纳押金
      wx.setStorageSync("no_pay_deposit", 0);
      console.log("-------------押金支付完成，重新连接，进行租赁", that.data.curBlueName)
      if (that.data.curBlueName) {
        that.setData({
          loading_show: true,
          loading_desc: '押金已缴纳,开始连接...',
          agentLeaseSelStatus: false,
          showModalStatus: false
        })
        that.connectBLEDevice(that.data.curBlueName)
      }
    } else if (msgVal == 6) {
      that.setData({
        showModalStatus: false,
        alertBoxStatus: false
      })
    }
  },
  alertUnRentBoxClose: function () {
    this.setData({
      unRentStatus: false
    })
  },
  /**
   * 等待接收蓝牙消息,进行开锁或归还操作
   * @param eqId
   * @param hid
   * @param costTime
   */
  openOrReturnEquitment: function (rfId, mac, costTime) {
    var that = this
    //服务端接口存在没有上传的数据为空
    if (!rfId) {
      //将接收到95数据的赋值
      rfId = that.data.rfid;
    }
    if (!mac) {
      //将扫码时获取的mac赋值
      mac = that.data.conMac;
    }
    if (!costTime) {
      //将接收到95数据时的赋值
      costTime = that.data.conBoxCostTime;
    }

    this.setData({
      rfId: rfId,
      modal: {
        modal_show: false,
        title: '温馨提示'
      }
    })

    that.setData({
      loading_show: true,
      loading_desc: '请稍等,处理数据中...',
      connectDesc: "请稍等,处理数据中...",
    })
    let startTime = new Date().getTime();
    app.executeRequest(function (header) {
      let startTimeOpenLock = new Date().getTime();
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/open_lock',
        method: 'post',
        header: header,
        data: {
          depositAutoBack: that.data.depositAutoBack,
          rfId: rfId,
          mac: mac,
          costTime: costTime,
          refund: that.data.refund,
          hookStatus: that.data.hookStatus,
          switchStatus: that.data.switchStatus,
          didiStat: that.data.didiStat,
          rfidIsCache: that.data.rfidIsCache,
          isScanBack: that.data.isScanBack,
        },
        success: function (res) {
          let openLockDiff = new Date().getTime() - startTimeOpenLock;
          let diff = new Date().getTime() - startTime;
          console.warn("开锁访问服务返回结果===========res=", res, diff, openLockDiff)

          common.clearConTimeCountTimer('112');

          let pile_id = that.data.pile_id ? 'Z' + that.data.pile_id : '';
          let errType = '';
          let netErr = app.handleRes(res, that);
          if (netErr) {
            return
          }
          if (that.data.canceledConnect) {
            that.recordBlueConnectError(10062, "用户中断连接2");
            return;
          }
          //记录校验结果日志
          setTimeout(function () {
            var logData = {
              reqNumber: 2,
              optDesc: "返回校验结果:" + JSON.stringify(res.data),
              rfid: rfId
            };
            that.connectLog(logData);
            that.recordBlueConnectError(ConstantData.err_type.open_lock_suc, "返回校验结果:" + JSON.stringify(res.data));
          }, 1000);

          var data = res.data

          that.data.no_eject_flg = data.no_eject;
          if (data.backSucVoiceUrl) {
            that.data.voiceTempFilePath = data.backSucVoiceUrl;
          }
          //未准确插入归位桩
          if (data.rst == -133) {
            //记录未准确插入桩的时间
            errType = ConstantData.err_type.open_lock_133;
            that.recordReturnBlueTimeoutError(2, '');
            app.globalData.isConnecting = false;
            BLELocker.disconnect('index2022');

            var nophone = app.getUserLoginNoPhone();
            if (nophone == null || nophone == undefined || nophone == 1) {
              wx.setStorageSync("alertBoxTipContent", data.errInfo);
              that.setData({
                phoneAuthStatus: true,
                phoneAuthBtt: 'no_return_blue_timeout',
                loading_show: false
              });
              wx.showToast({
                title: '请先登录',
                icon: 'none'
              })
              return;
            }

            that.setData({
              alertBoxStatus: true,
              alertBoxTipContent: data.errInfo + errType,
              msgRst: 6,
              alertBoxBtnName: '确  定'
            });
            return
          }

          if (data.rst == 12) { //帮代租设备已成功归还
            app.globalData.isConnecting = false;
            BLELocker.disconnect('index2043')
            that.setData({
              alertBoxStatus: true,
              alertBoxTipContent: '帮代租设备已成功归还',
              msgRst: 6,
              alertBoxBtnName: '确  定',
              wxDeviceId: data.deviceId,
              wxConnType: data.connType
            })
            return
          }

          if (data.rst == '-138') { //帮代租设备已成功归还
            app.globalData.isConnecting = false;
            BLELocker.disconnect('index2676')
            that.setData({
              showDialog: true,
              alertBoxTipContent: data.eqId,
              // msgRst: 6,
              alertBoxBtnName: '重新扫码',
              wxDeviceId: data.deviceId,
              wxConnType: data.connType
            })
            return
          }

          if (data.rst == 13) {
            errType = ConstantData.err_type.open_lock_13;
            app.globalData.isConnecting = false;
            BLELocker.disconnect('index2280')
            that.setData({
              modal: {
                modal_show: true,
                desc: data.errInfo ? data.errInfo : '当前时间不可租借' + errType,
                confirm: true
              }
            })
            return;
          }
          if (data.rst == 14) {
            errType = ConstantData.err_type.open_lock_14;
            that.setData({
              modal: {
                modal_show: true,
                desc: data.errInfo ? data.errInfo : '您的操作过于频繁，请稍候再试' + errType,
                confirm: true
              }
            })
            return;
          }
          console.log('elecInt---------homeMinLeftElectricity', that.data.elecInt, data.homeMinLeftElectricity)
          if (that.data.elecInt < data.homeMinLeftElectricity) {
            errType = ConstantData.err_type.open_lock_15;
            app.globalData.isConnecting = false;
            BLELocker.disconnect('index2056')
            that.setData({
              alertBoxStatus: true,
              alertBoxTipContent: '正安排更换电池,请租赁其他设备' + pile_id + '-' + errType
            })

            that.recordBlueConnectError(errType, "开锁:正安排更换电池,请租赁其他设备,mac=" + mac + "," + that.data.elecInt + "," + data.homeMinLeftElectricity)

            return;
          }

          //判断是否存在绑定的账号，存在则弹出选择的列表
          var bindUserList = data.bindUserInfoList
          var agentEmployerList = data.agentEmployerList
          if (agentEmployerList && agentEmployerList.length > 0) {
            var sureLeaseTipInfo = '请提醒用户及时归还'
            //门诊爱心租赁列表
            that.setData({
              bindUserType: 2,
              bindUserListStatus: true,
              mapShowStatus: false,
              showModalStatus: false,
              agentLeaseSelStatus: false,
              bindUserList: agentEmployerList,
              wxDeviceId: data.deviceId,
              wxConnType: data.connType,
              wxEqId: data.eqId,
              wxHid: data.hid,
              wxEqTid: data.eqTid,
              leftTimeLenStr: sureLeaseTipInfo
            })
            return
          }

          if (bindUserList && bindUserList.length > 0) {
            //包时卡绑定用户
            that.setData({
              bindUserType: 1,
              bindUserListStatus: true,
              mapShowStatus: false,
              showModalStatus: false,
              agentLeaseSelStatus: false,
              bindUserList: bindUserList,
              wxDeviceId: data.deviceId,
              wxConnType: data.connType,
              wxEqId: data.eqId,
              wxHid: data.hid,
              wxEqTid: data.eqTid
            })
            return
          }

          var leaseSatus = data.closeDoorTip ? false : true;
          var systemInfo = wx.getStorageSync('systeminfo');
          var isCouldNoDeposit = util.isCouldNoDeposit(systemInfo);
          var isAllowNoDeposit = isCouldNoDeposit && data.wxNoDeposit == 1;
          console.log("-----isAllowNoDeposit=", isAllowNoDeposit);
          that.setData({
            isAllowNoDeposit: isAllowNoDeposit
          })

          let equTipInfo = data.equTipInfo;
          if (equTipInfo) {
            that.setData({
              //提示的图片列表
              imgUrls: equTipInfo.tipImgList,
              //是否显示轮播图的点
              indicatorDots: equTipInfo.tipImgList.lenght > 1,
              //提示的标题
              tipTitle: equTipInfo.title,
              //提示描述说明信息
              tipList: equTipInfo.tipList,
            })
          }

          if (data.rst == 0) {
            console.log("chareRuleInfo----=" + data.chargeRuleInfo)
            console.log(data)
            var chargeRuleInfo = data.chargeRuleInfo
            //已支付押金
            wx.setStorageSync("no_pay_deposit", 0);
            that.setData({
              bindUserType: 0,
              isPayDeposit: true,
              openLockLeaseOptStatus: true,
              chargeRuleTitle: data.chargeRuleTitle,
              chargeContent: chargeRuleInfo,
              showModalStatus: leaseSatus,
              hospitalTipBox: !leaseSatus,
              closeTipInfo: data.closeDoorTip,
              mapShowStatus: false,
              bindUserListStatus: false,
              agentLeaseSelStatus: false,
              bindUserList: [],
              wxDeviceId: data.deviceId,
              wxConnType: data.connType,
              wxEqId: data.eqId,
              wxHid: data.hid,
              wxEqTid: data.eqTid,
              serviceUuid: data.homing_uuid,
              homingFEC7: data.homing_FEC7,
              homingFEC8: data.homing_FEC8,
              homingFEC9: data.homing_FEC9,
              ruleList: data.ruleList,
              ruleDesc: data.ruleDesc,
              leaseMaxPriceStr: data.leaseMaxFeeStr,
              loading_show: false,
            })
            if (data.isSilenceBack == 1) {
              that.setData({
                isReturn: that.data.isReturn + 1
              })
            } else {
              that.setData({
                isReturn: 0
              })
              wx.removeStorageSync('no_eject_times')
            }
            if (that.data.isReturn) {
              console.log("--remove-rst0-noback")
              wx.removeStorageSync('user_no_back');
              that.setData({
                connectType: '租借'
              })
              // 一分钟租借次数
              if (that.data.isReturn > 2) {
                that.data.modal.desc = "设备" + pile_id + "网络异常，请换一台租赁"
                that.data.modal.desc_mini = "一分钟-" + ConstantData.err_type.open_lock_one_min;
                that.data.modal.modal_show = true
                that.data.modal.confirm = true
                that.setData({
                  modal: that.data.modal,
                  showModalStatus: false
                })
                that.recordBlueConnectError(ConstantData.err_type.open_lock_one_min, 'modalErr:连续3次一分钟租借');
              }
            }


            BLELocker.setHomingDeviceServiceInfo(data.homing_uuid, data.homing_FEC7, data.homing_FEC8, data.homing_FEC9)

          } else {
            console.log("openLock statRst=" + data.rst)
            if (data.rst == 11) { //租赁记录支付完成
              app.globalData.isConnecting = false;
              BLELocker.disconnect('index2179')
              that.setData({
                // alertBoxStatus: true,
                // alertBoxTipContent: data.tName + '已归位成功,租金已支付',
                msgRst: 1,
                alertBoxBtnName: '确  定',
                wxDeviceId: data.deviceId,
                wxConnType: data.connType,
                refundTip: that.data.refund, //1在租赁页面弹toast提示
                refund: 0,
                isBackChairStatus: false,
                refundEqTid: data.eqTid
              })


              that.registerAudioContext();
              wx.navigateTo({
                url: 'lease_tip/lease_tip?pt=back&equId=' + data.eqId + "&rent=" + data.rent + "&backtime=" + data.backTime + "&opentime=" + data.openTime + "&costtime=" + data.timeLenStr + "&depositBackSuc=" + data.isAutoRefund +
                  '&lockType=' + that.data.lockType + '&backSucDesc=' + data.backSucDesc + '&backSucVoiceUrl=' + data.backSucVoiceUrl,
              });


            } else if (data.rst == 1) { //归还设备,跳转到租金列表进行支付
              app.globalData.isConnecting = false;
              BLELocker.disconnect('index2198')
              that.setData({
                // alertBoxStatus: true,
                // alertBoxTipContent: data.tName + '已归位成功,请去支付租金',
                msgRst: 1,
                isBackChairStatus: false,
                alertBoxBtnName: '确  定',
                wxDeviceId: data.deviceId,
                wxConnType: data.connType
              })
              let rentInfo = {};
              rentInfo.backTime = data.backTime;
              rentInfo.borrowTime = data.openTime;
              rentInfo.costTime = data.timeLenStr;
              rentInfo.deposit = data.deposit;
              rentInfo.orderCode = data.orderCode;
              rentInfo.rent = data.rent;
              rentInfo.noPayTitle = data.noPayTitle;
              rentInfo.priceLabel = data.priceLabel;
              rentInfo.orderType = data.orderType;
              rentInfo.inCycleLeaseTimeLen = data.inCycleLeaseTimeLen || '';
              rentInfo.inCycleRecordInfoList = data.inCycleRecordInfoList || [];
              rentInfo.noPayDepositTip = data.noPayDepositTip;
              rentInfo.depositBackSuc = data.isAutoRefund;
              rentInfo.backSucVoiceUrl = data.backSucVoiceUrl;
              wx.navigateTo({
                url: 'no_pay_tip/no_pay_tip?rentInfo=' + JSON.stringify(rentInfo)
              })

            } else if (data.rst == 2) { //同类设备只准租一个,提示用户归还的时候也需要扫一下二维码
              errType = ConstantData.err_type.open_lock_2;
              app.globalData.isConnecting = false;
              BLELocker.disconnect('index2214')
              if (data.leaseNoBackInfo) {
                //未归还的
                if (that.data.pt == 'noback' || (data.eqId && data.eqId != data.leaseNoBackInfo.equId)) {
                  that.setData({
                    modal: {
                      modal_show: true,
                      desc_mini: errType,
                      desc: "请核对轮椅右侧编号，找到L" + data.leaseNoBackInfo.equId + "，这个L" + data.leaseNoBackInfo.equId + "轮椅锁在哪个桩位上，就扫哪个桩位玻璃面板上大的二维码就可以归还成功了",
                      confirm: true,
                      desc_center: true
                    }
                  })
                } else {
                  console.log("跳转---》未归还页面")
                  wx.navigateTo({
                    url: 'no_back_tip/no_back_tip?equId=' + data.leaseNoBackInfo.equId + "&positions=" + data.leaseNoBackInfo.positions + "&hospitalName=" + data.leaseNoBackInfo.hospitalName + "&orderCode=" + data.orderCode,
                  })
                }
              } else {
                that.setData({
                  alertBoxStatus: true,
                  alertBoxTipContent: '很抱歉,您有未归还的' + data.tName,
                  msgRst: 2,
                  isBackChairStatus: true,
                  alertBoxBtnName: '去归还'
                })
              }
            } else if (data.rst == 4 || data.rst == 5) { //同类设备只准租一个,提示用户归还的时候也需要扫一下二维码
              app.globalData.isConnecting = false;
              BLELocker.disconnect('index2242')
              that.setData({
                // alertBoxStatus: true,
                // alertBoxTipContent: '很抱歉,您有未付租金的' + data.tName,
                msgRst: 4,
                // alertBoxBtnName: '付租金'
              })
              console.log('data------------------------------------>', data)
              let rentInfo = {};
              rentInfo.backTime = data.backTime;
              rentInfo.borrowTime = data.openTime;
              rentInfo.costTime = data.timeLenStr;
              rentInfo.deposit = data.deposit;
              rentInfo.orderCode = data.orderCode;
              rentInfo.rent = data.rent;
              rentInfo.noPayTitle = data.noPayTitle;
              rentInfo.priceLabel = data.priceLabel;
              rentInfo.orderType = data.orderType;
              rentInfo.inCycleLeaseTimeLen = data.inCycleLeaseTimeLen || '';
              rentInfo.inCycleRecordInfoList = data.inCycleRecordInfoList || [];
              rentInfo.depositBackSuc = data.isAutoRefund;
              wx.navigateTo({
                url: 'no_pay_tip/no_pay_tip?rentInfo=' + JSON.stringify(rentInfo)
              }) //0718mark--跳转到支付租金页面
            } else if (data.rst == 3) { //未交押金
              wx.setStorageSync("no_pay_deposit", 1);
              that.setData({
                callServiceTipContent: data.tName + "租赁需缴纳押金  ￥" + data.deposit,
                equId: data.eqId,
                toPayDeposit: !isAllowNoDeposit,
                isPayDeposit: false,

                bindUserType: 0,
                openLockLeaseOptStatus: true,
                chargeRuleTitle: data.chargeRuleTitle,
                chargeContent: data.chargeRuleInfo,
                showModalStatus: leaseSatus,
                hospitalTipBox: !leaseSatus,
                closeTipInfo: data.closeDoorTip,
                mapShowStatus: false,
                bindUserListStatus: false,
                agentLeaseSelStatus: false,
                bindUserList: [],
                wxDeviceId: data.deviceId,
                wxConnType: data.connType,
                wxEqId: data.eqId,
                wxHid: data.hid,
                wxEqTid: data.eqTid,
                serviceUuid: data.homing_uuid,
                homingFEC7: data.homing_FEC7,
                homingFEC8: data.homing_FEC8,
                homingFEC9: data.homing_FEC9,
                ruleList: data.ruleList,
                ruleDesc: data.ruleDesc,
                leaseMaxPriceStr: data.leaseMaxFeeStr,
                isReturn: data.isSilenceBack == 1
              })
              console.log('88888888888888')
              if (!that.data.isReturn) {
                wx.removeStorageSync('no_eject_times')
              }
              console.log('that.data.isPayDeposit--->>', that.data.isPayDeposit)
            } else if (data.rst == -102) {
              errType = ConstantData.err_type.open_lock_102;
              app.globalData.isConnecting = false;
              BLELocker.disconnect('index2289')
              var desc = data.errInfo ? data.errInfo : "设备维护中,请换其它桩租赁";
              that.setData({
                modal: {
                  modal_show: true,
                  desc_mini: "L" + data.eqId + "维护中" + errType,
                  desc: desc,
                  confirm: true,
                  desc_center: true
                }
              })

              that.recordBlueConnectError(errType, "开锁:设备维护中,请扫描其他设备,-102")

            } else if (data.rst == -104) {
              errType = ConstantData.err_type.open_lock_104;
              app.globalData.isConnecting = false;
              BLELocker.disconnect('index2300')
              that.setData({
                modal: {
                  modal_show: true,
                  desc: "很抱歉,非法设备(" + (rfId ? rfId : '') + ")无法处理" + errType,
                  confirm: true,
                  desc_center: true
                }
              })

              that.recordBlueConnectError(errType, "开锁:很抱歉,非法设备无法处理,-104")

            } else if (data.rst == -137) {
              that.hideModal1()
              let user_no_back = wx.getStorageSync('user_no_back');
              let errType = '';
              if (user_no_back) {
                if (that.data.switchStatus == 0) {
                  let insert_fail_time = wx.getStorageSync('insert_fail_time') || 1
                  wx.setStorageSync('insert_fail_time', insert_fail_time + 1)
                  if (that.data.no_eject_back_flg == 2) {
                    insert_fail_time = 5;
                  }
                  //第3次
                  if (insert_fail_time > 2) {
                    errType = ConstantData.err_type.open_lock_137_insert_back_times;
                    that.data.modal.desc = "请确认设备已经锁好且拉不下来后可联系客服帮您归还。";
                    that.data.modal.desc_mini = "inSwitch " + pile_id + "-" + errType;
                    that.data.modal.modal_show = true
                    that.data.modal.contact = true
                  } else {
                    errType = ConstantData.err_type.open_lock_137_insert_back;
                    that.data.modal.desc = "1、请检查设备是不是已经锁好。\n2、如果已经锁住，请将轮椅摆正，然后往里推着轮椅点击重试。";
                    that.data.modal.desc_mini = "inSwitch " + pile_id + "-" + errType;
                    that.data.modal.desc_center = false
                    that.data.modal.modal_show = true
                    that.data.modal.img2_show = true
                    that.data.modal.retry95 = true
                  }
                  that.setData({
                    loading_show: false,
                    modal: that.data.modal,
                  })
                } else if (that.data.hookStatus == 1) {
                  //轮椅未锁好
                  // if(that.data.lockType){
                  //   that.setData({
                  //     show_lockType:true
                  //   })
                  // }
                  that.data.no_eject_back_flg = data.no_eject_back_flg ? data.no_eject_back_flg : '';
                  if (that.data.no_eject_back_flg == 1) {
                    //如果是同一用户同一桩位同一轮椅，且三分钟之内，则显示未弹出弹框，给用户再发一次85的机会
                    errType = ConstantData.err_type.open_lock_137_hook_noeject_inner;
                    console.warn('--三分钟之内，显示未弹出弹框');
                    that.setData({
                      modal: {
                        modal_show: true,
                        desc: '1、如未弹出，请点击“重试租借”再租借一次，\n2、如已弹出，请点击“设备已弹出”。\n3、请慎重选择，如果不做操作，我们将默认为设备已弹出。',
                        desc_mini: pile_id + '-' + errType,
                        desc_center: false,
                        sucOpen: true,
                        retry85: true
                      }
                    })
                    that.recordBlueConnectError(errType, '锁钩开关故障归还失败，三分钟之内，显示“未弹出弹框”');
                    return;
                  } else if (that.data.no_eject_back_flg == 2) {
                    //如果是同一用户同一桩位同一轮椅，且三分钟之后，则直接提示联系客服进行归还
                    errType = ConstantData.err_type.open_lock_137_hook_noeject_out;
                    console.warn('--三分钟之后，提示联系客服');
                    that.data.modal.modal_show = true
                    that.data.modal.desc = "请确认设备已经锁好且拉不下来后可联系客服帮您归还";
                    that.data.modal.desc_mini = "hookSwitch " + pile_id + "-" + errType;
                    that.data.modal.contact = true
                    that.setData({
                      openning_show: false,
                      loading_show: false,
                      modal: that.data.modal,
                    })
                    that.recordBlueConnectError(errType, '锁钩开关故障归还失败，三分钟之后，显示“联系客服归还”');
                    return;
                  }

                  let hook_fail_time = wx.getStorageSync('hook_fail_time') || 1
                  wx.setStorageSync('hook_fail_time', hook_fail_time + 1)
                  if (hook_fail_time > 2) {
                    //第3次
                    errType = ConstantData.err_type.open_lock_137_hook_back_times;
                    that.data.modal.modal_show = true
                    that.data.modal.desc = "请确认设备已经锁好且拉不下来后可联系客服帮您归还";
                    that.data.modal.desc_mini = "hookSwitch " + pile_id + "-" + errType;
                    that.data.modal.contact = true
                  } else {
                    errType = ConstantData.err_type.open_lock_137_hook_back;
                    that.data.modal.desc = "请将轮椅摆正，将轮椅往里推一推，再左右摇晃轮椅。完成上述操作后点击重试。";
                    that.data.modal.desc_mini = "hookSwitch " + pile_id + "-" + errType;
                    that.data.modal.modal_show = true
                    that.data.modal.img3_show = true
                    that.data.modal.retry95 = true
                  }
                  that.setData({
                    loading_show: false,
                    modal: that.data.modal,
                  })
                } else {
                  errType = ConstantData.err_type.open_lock_137_else;
                  that.setData({
                    modal: {
                      modal_show: true,
                      desc: data.errInfo ? data.errInfo : '归还失败',
                      desc_mini: pile_id + '-' + errType,
                      desc_center: false,
                      confirm: true,
                    }
                  })
                  wx.removeStorageSync('insert_fail_time')
                  wx.removeStorageSync('hook_fail_time')
                }
              } else {
                if (that.data.switchStatus == 0) {
                  // if(that.data.lockType){
                  //   that.setData({
                  //     show_lockType:true
                  //   })
                  // }
                  let insert_fail_time = wx.getStorageSync('insert_fail_time') || 1
                  wx.setStorageSync('insert_fail_time', insert_fail_time + 1)
                  //第3次
                  if (insert_fail_time > 2) {
                    errType = ConstantData.err_type.open_lock_137_insert_rent_times;
                    that.data.modal.desc = "请换一个设备租赁";
                    that.data.modal.desc_mini = "inSwitch " + pile_id + "-" + errType;
                    that.data.modal.modal_show = true
                    that.data.modal.contact = true
                  } else {
                    errType = ConstantData.err_type.open_lock_137_insert_rent;
                    that.data.modal.desc = "1、请检查设备是不是已经锁好。\n2、如果已经锁住，请将轮椅摆正，然后往里推着轮椅点击重试。";
                    that.data.modal.desc_mini = "inSwitch " + pile_id + "-" + errType;
                    that.data.modal.desc_center = false
                    that.data.modal.modal_show = true
                    that.data.modal.img2_show = true
                    that.data.modal.retry95 = true
                  }
                  that.setData({
                    loading_show: false,
                    modal: that.data.modal,
                  })
                } else if (that.data.hookStatus == 1) {
                  //轮椅未锁好
                  let hook_fail_time = wx.getStorageSync('hook_fail_time') || 1
                  wx.setStorageSync('hook_fail_time', hook_fail_time + 1)
                  if (that.data.no_eject_back_flg == 2) {
                    hook_fail_time = 5;
                  }
                  if (hook_fail_time > 2) {
                    //第3次
                    errType = ConstantData.err_type.open_lock_137_hook_rent_times;
                    that.data.modal.modal_show = true
                    that.data.modal.desc = "请换一个设备租赁";
                    that.data.modal.desc_mini = "hookSwitch " + pile_id + "-" + errType;
                    that.data.modal.contact = true
                  } else {
                    errType = ConstantData.err_type.open_lock_137_hook_rent;
                    that.data.modal.desc = "请将轮椅摆正，将轮椅往里推一推，再左右摇晃轮椅。完成上述操作后点击重试。";
                    that.data.modal.desc_mini = "hookSwitch " + pile_id + "-" + errType;
                    that.data.modal.modal_show = true
                    that.data.modal.img3_show = true
                    that.data.modal.retry95 = true
                  }
                  that.setData({
                    loading_show: false,
                    modal: that.data.modal,
                  })
                } else {
                  errType = ConstantData.err_type.open_lock_137_else_rent;
                  that.setData({
                    modal: {
                      modal_show: true,
                      desc: data.errInfo ? data.errInfo : '租借失败',
                      desc_mini: pile_id + '-' + errType,
                      desc_center: false,
                      confirm: true,
                    }
                  })
                  wx.removeStorageSync('insert_fail_time')
                  wx.removeStorageSync('hook_fail_time')
                }
              }
              that.recordBlueConnectError(errType, "开锁:" + that.data.isBackChairStatus + "," + data.rst)
            } else if (data.rst == 20) {
              //归还成功后断开蓝牙
              app.globalData.isConnecting = false;
              BLELocker.disconnect('index2564');
              //代归还成功
              var desc = data.errInfo ? data.errInfo : "归还成功!";
              that.setData({
                alertBoxStatus: true,
                alertBoxTipContent: desc,
                connectType: '归还',
                alertBoxBtnName: '确  定'
              });
              that.recordBlueConnectError(ConstantData.err_type.open_lock_help_back, desc);

            } else if (data.rst == 21) {
              //点击归还扫码按钮,未绑定手机号
              wx.showModal({
                title: '温馨提示',
                content: '未绑定手机号,请先登录',
                success(res) {
                  if (res.confirm) {
                    //去登录页面
                    wx.navigateTo({
                      url: '../login/login',
                    })
                  } else if (res.cancel) {
                    console.log('用户点击取消')
                  }
                }
              })



            } else {
              errType = ConstantData.err_type.open_lock_else;
              app.globalData.isConnecting = false;
              BLELocker.disconnect('index2366');
              var desc = data.errInfo ? data.errInfo : "请扫码重试";
              that.setData({
                alertBoxStatus: true,
                alertBoxTipContent: desc + errType,
                alertBoxBtnName: '确  定'
              })

              that.recordBlueConnectError(errType, "开锁:" + desc + "," + data.rst)
            }
          }
        },
        fail: function (res) {
          wx.showToast({
            title: '网络异常请重试',
          })
        },
        complete: function (res) {
          if (that.data.canceledConnect) {
            that.recordBlueConnectError(10062, "用户中断连接2");
            return;
          }
          that.setData({
            loading_show: false
          })

          setTimeout(function () {
            that.recordBlueConnectError(ConstantData.err_type.open_lock_res, "开始请求是否符合开锁租赁条件" + rfId + ' 请求结果:' + (res.data ? res.data.rst : '空'));
          }, 300);

        }
      })

    })

  },
  /**
   * 选择包时卡绑定账号的变更
   */
  bindUserChange: function (e) {
    var val = e.detail.value
    var user = this.data.bindUserList[val[0]]

    console.warn(user)

    if (!user.bindUid) {
      wx.showToast({
        title: '请重新选择',
      })
      return
    }

    this.setData({
      user_tab: user.bindTag,
      selBindUserId: user.bindUid,
      checkboxStatus: 'checkboxSelected',
      selBindUser: user
    })
  },
  /**
   * 绑定包时卡的账号确定开锁
   */
  bindUserChangeSure: function () {
    if (this.data.selBindUserId == 0) {
      this.setData({
        selBindUserId: this.data.bindUserList[0].bindUid,
        selBindUser: this.data.bindUserList[0]
      })
    }

    this.setData({
      agentLeaseSelStatus: false,
      isPayDeposit: true,
    })

    var selBindUid = this.data.selBindUserId
    console.log("代租赁,开始开锁------")
    console.log(selBindUid)

    this.openLock()
  },
  /**
   * 绑定包时卡账号取消选择
   */
  cancelAgentLease: function () {
    app.globalData.isConnecting = false;
    BLELocker.disconnect('index1032')
    this.setData({
      agentLeaseSelStatus: false,
      bindUserListStatus: false,
      mapShowStatus: true,
    })
  },
  /**
   * 确定租赁
   */
  sureToAgentLease: function () {
    this.setData({
      cancelAgentSelLeaseStatus: false,
      isPayDeposit: true
    })

    var that = this
    var selBindUid = this.data.selBindUserId
    var selUser = this.data.selBindUser
    if (selBindUid == 0) {
      selUser = this.data.bindUserList[0]
    }
    //绑定类型2爱心租赁，1包时卡租赁
    var bindType = 1
    var timeLenStr = ''
    if (selUser.employerUid) {
      //爱心租赁的
      bindType = 2
    } else {
      //绑卡代租的
      bindType = 1
    }

    var eqTid = this.data.wxEqTid
    console.log("确认完选择的代租用户--" + eqTid + "," + selUser.bindUid)
    this.validateBindNoPayOrNoReturn(selUser, eqTid, bindType)
  },
  /**
   * 校验包时卡或门诊爱心租赁是否存在未支付或未归还的
   */
  validateBindNoPayOrNoReturn: function (selUser, eqTid, bindType) {
    var that = this

    var cardTimeLen = selUser.cardTimeLen
    var timeLenStr = this.data.leftTimeLenStr
    var noPayStrSuffix = ''
    if (bindType == 1) {
      //包时卡的时长信息
      timeLenStr = selUser.bindPhone + '(' + selUser.bindTag + '),剩余时长:'
      if (cardTimeLen < 60) {
        timeLenStr += cardTimeLen + '分钟'
      } else {
        timeLenStr += parseInt(cardTimeLen / 60) + '小时'
      }

      noPayStrSuffix = ',请电话告知用户购买包时卡后才能再借用!'
    } else if (bindType == 2) {
      noPayStrSuffix = ',请完成支付再租借!'
    }

    app.executeRequest(function (header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_time_card/nopay',
        method: 'post',
        header: header,
        data: {
          buid: selUser.bindUid,
          tid: eqTid,
          bindType: bindType
        },
        success: function (res) {
          console.log(res)
          let netErr = app.handleRes(res, that);
          if (netErr) {
            return
          }
          var result = res.data.data
          var noPayTimeLen = result.noPayTimeLen
          var noReturnCount = result.noReturnCount
          var depositPayRst = result.depositPayRst
          var cardTimeLen = result.cardTimeLen
          var noReturnEquId = result.noReturnEquId
          var equTypeName = result.equTypeName
          var isCouldLease = true
          var noPayTipStatus = false
          var noPayTimeLenStr = ''
          var noLeaseTipInfo = ''
          if (cardTimeLen <= 0 && bindType == 1) {
            //包时卡时间不足
            isCouldLease = false
            noPayTipStatus = true
            noLeaseTipInfo = '包时卡已用完，不能为他(代租)，请电话通知家属购买包时卡'
          } else if (depositPayRst <= 0) {
            //未交押金
            isCouldLease = false
            noPayTipStatus = true
            noLeaseTipInfo = '该用户押金还未支付,不能租借'
          } else if (noReturnEquId > 0) {
            //存在未归还设备
            noLeaseTipInfo = '该用户有租借的' + noReturnEquId + '号' + equTypeName + '没有归还,不能租借'
            isCouldLease = false
            noPayTipStatus = true
          } else if (noPayTimeLen && noPayTimeLen > 0) {
            //存在未支付的订单
            isCouldLease = false
            noPayTipStatus = true
            if (noPayTimeLen < 60) {
              noPayTimeLenStr = noPayTimeLen + '分钟'
            } else {
              noPayTimeLenStr = parseInt(noPayTimeLen / 60) + '小时'
            }
            noLeaseTipInfo = '该用户已欠费(有' + noPayTimeLenStr + '时长未付款)' + noPayStrSuffix
          } else {
            //可以正常租赁
          }

          that.setData({
            selBindUserId: selUser.bindUid,
            user_tab: selUser.bindTag,
            leftTimeLenStr: timeLenStr,
            agentLeaseSelStatus: true,
            showModalStatus: false,
            bindUserListStatus: false,
            mapShowStatus: false,
            leaseBtnStatus: isCouldLease,
            noPayTimeTipStatus: noPayTipStatus,
            noPayTimeLenStr: noPayTimeLenStr,
            noLeaseTipInfo: noLeaseTipInfo
          })
        },
        fail: function (res) {
          wx.showToast({
            title: '稍后重试',
          })
        }
      })

    })

  },
  /**
   * 取消打电话
   */
  cancelCallPhone: function () {
    this.setData({
      callConsumePhoneBoxStatus: false
    })
  },
  /**
   * 拨打客服电话
   */
  callConsumePhone: function () {
    this.setData({
      callConsumePhoneBoxStatus: false
    })
    var phone = this.data.mainConsumerPhone
    wx.makePhoneCall({
      phoneNumber: phone
    })
  },
  /**
   * 取消代租赁
   */
  cancelAgentSelLease: function () {
    console.log("取消包时卡代租的选择-----------------")
    if (this.data.cancelAgentSelLeaseStatus) {
      app.globalData.isConnecting = false;
      BLELocker.disconnect('index2600');
      this.setData({
        selBindUserId: 0,
        agentLeaseSelStatus: false,
        bindUserListStatus: false,
        mapShowStatus: true,
        cancelAgentSelLeaseStatus: true
      })
    }
  },
  cancelPayDeposit: function () {
    app.globalData.isConnecting = false;
    BLELocker.disconnect('index2611')
    this.setData({
      openning_show: false,
      callServiceBoxStatus: false,
      hideIsDisconnectStat: true,
      payDepositBtnStatus: true,
      payDepositBtnTxt: "去缴纳",
      noDepositFail: false,
      loading_show: false
    })

    this.recordBlueConnectError(ConstantData.err_type.deposit_pay_close, "取消押金支付")
    console.log('cancelPayDeposit----->>', this.data.isAllowNoDeposit, this.data.noDepositFail)
  },
  toPayDeposit: function (event) {
    if (!this.data.payDepositBtnStatus) {
      return;
    }
    var that = this
    console.log("去支付。。。equTid=")

    that.data.payDepositBtnStatus = false

    var total_micro_second = 59 * 1000;
    payDepositSecondCountDown(this, total_micro_second)

    app.executeRequest(function (header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_dposit/wxmini/to_pay',
        method: 'post',
        header: header,
        data: {
          eqId: that.data.equId
        },
        success: function (res) {
          console.log('/lease_dposit/wxmini/to_pay----->', res)
          let netErr = app.handleRes(res, that);
          if (netErr) {
            return
          }
          var data = res.data
          if (data.result == 0) {
            that.toPay(data.data)
          } else if (data.result == -1) {
            wx.navigateTo({
              url: '../user_record/deposit/user_deposit',
            })
          } else {
            that.setData({
              alertBoxStatus: true,
              alertBoxTipContent: data.description,
              payDepositBtnStatus: true,
              payDepositBtnTxt: "去缴纳"
            })
          }

        },
        fail: function () {
          that.setData({
            payDepositBtnStatus: true,
            payDepositBtnTxt: "去缴纳"
          })
        }
      })

    })
  },

  payDepositSuccess() {
    var that = this

    if (that.data.checkPayStatusInterval) {
      clearInterval(that.data.checkPayStatusInterval);
    }
    that.setData({
      checkPayStatusInterval: null,
    });

    that.recordBlueConnectError(ConstantData.err_type.deposit_pay_confirm, "[押金]支付成功")
    that.getSubscribeMessage('押金支付成功', function () {
      that.setData({
        openning_show: true, //0806冯慧敏，押金支付成功即显示开锁中
        openning_desc: '押金支付成功,准备开锁...',
        callServiceBoxStatus: false,
        payDepositBtnStatus: true,
        payDepositBtnTxt: "去缴纳",
        isPayDeposit: true
      })
      wx.setStorageSync("no_pay_deposit", 0);
      that.recordBlueConnectError(ConstantData.err_type.deposit_pay_success, '押金支付成功,准备开锁...');
      if (that.data.noDepositFail) {
        that.setData({
          noDepositFail: false
        })
      }

      if (that.data.isColonyCon) {
        that.recordBlueConnectError(ConstantData.err_type.deposit_pay_success_openlock, "[开锁]gateway开始直接开锁-押金支付成功");
        that.leaseEquipment(true);
        return;
      }

      //判断是否还在连接，连接着的直接开锁进行租赁
      wx.getConnectedBluetoothDevices({
        services: ['FEE7'],
        success: function (res) {
          console.log("111----current connected blue " + JSON.stringify(res))
          if (res.devices && res.devices.length > 0) {
            //展示收费规则提示框
            that.setData({
              payDepositStat: true,
              showModalStatus: false,
              mapShowStatus: false,
              hideIsDisconnectStat: false,
              bindUserListStatus: false,
              agentLeaseSelStatus: false,
              isPayDeposit: true
            })
            that.recordBlueConnectError(ConstantData.err_type.deposit_pay_success_openlock, "[开锁]开始直接开锁-押金支付成功");
            that.leaseEquipment(true);
          } else {
            that.recordBlueConnectError(ConstantData.err_type.deposit_pay_success_connect, "[连接]没有设备,重新连接-押金支付成功")
            connectCurrentBlue(that)
          }
        },
        fail: function () {
          that.recordBlueConnectError(ConstantData.err_type.deposit_pay_success_reconnect, "[连接]获取失败,重新连接-押金支付成功")
          connectCurrentBlue(that)
        }
      })
    });
  },

  toPay: function (orderCode) {
    var that = this
    console.log("去支付。。。" + orderCode);

    app.toPayValideLogin(orderCode, function (loginCode, orderCode, err) {

      app.executeRequest(function (header) {

        wx.request({
          url: ConstantData.CONSTATNT_DATA.BASE_URL + '/ejiam/wxmini/weixin/pay',
          method: 'post',
          header: header,
          data: {
            orderCode: orderCode,
            loginCode: loginCode,
            wxErr: err
          },

          success: function (res) {
            let netErr = app.handleRes(res, that);
            if (netErr) {
              return
            }
            var data = res.data
            console.log("支付结果---" + data.result)
            if (data.result != 0 || !data.data || !data.data.timeStamp) {
              that.setData({
                alertBoxStatus: true,
                alertBoxTipContent: data.description ? data.description : '押金支付失败'
              })
              that.recordBlueConnectError(ConstantData.err_type.deposit_pay_fail, '押金支付请求失败')
              return
            }
            that.setData({
              hideIsDisconnectStat: false, //支付成功后隐藏不关闭蓝牙
              openning_show: true, //200114 冯慧敏，押金支付之前就显示开锁中，以防止押金支付成功后用户有机会再次点击扫码，影响开锁
              openning_desc: '正在支付押金...',
            })

            if (that.data.checkPayStatusInterval) {
              clearInterval(that.data.checkPayStatusInterval);
            }
            that.setData({
              isPayDepositSuccess: false,
              checkPayStatusInterval: null,
            });
            let checkPayStatusInterval = setInterval(() => {
              console.log('【轮询押金支付状态】');
              if (that.data.isPayDepositSuccess) {
                if (that.data.checkPayStatusInterval) {
                  clearInterval(that.data.checkPayStatusInterval);
                }
                that.setData({
                  checkPayStatusInterval: null,
                });
                return;
              }

              noDepositLease.queryPayDepositStatus(orderCode).then(res => {
                console.log('【押金支付状态查询】已支付...' + res);
                that.setData({
                  isPayDepositSuccess: true,
                });
                that.payDepositSuccess();
              }).catch(error => {
                console.log('【押金支付状态查询】未支付...' + error);
              })

            }, 1000);
            that.setData({
              checkPayStatusInterval: checkPayStatusInterval
            });

            wx.requestPayment({
              appId: 'wx0e458dc331e557cc',
              timeStamp: data.data.timeStamp,
              nonceStr: data.data.nonceStr,
              package: data.data.package,
              signType: data.data.signType,
              paySign: data.data.paySign,
              success: function (res) {
                if (that.data.isPayDepositSuccess) {
                  that.getSubscribeMessage('押金支付成功', null);
                  return;
                }
                that.payDepositSuccess();
              },
              fail: function (res) {
                that.recordBlueConnectError(ConstantData.err_type.deposit_pay_cancel, "押金FAIL:" + JSON.stringify(res))
                that.setData({
                  openning_show: false,
                  hideIsDisconnectStat: false,
                  payDepositBtnStatus: true,
                  payDepositBtnTxt: "去缴纳"
                })
                common.recordErrorInfo(ConstantData.err_type.pay_fail, res ? 'index2-' + JSON.stringify(res) : '');

                if (that.data.checkPayStatusInterval) {
                  clearInterval(that.data.checkPayStatusInterval);
                }
              },
              complete: function (res) {
                that.setData({
                  hideIsDisconnectStat: false,
                  payDepositBtnStatus: true,
                  payDepositBtnTxt: "去缴纳"
                })
                console.log("complete--" + data.data.paySign)
                console.log(res)

                if (that.data.checkPayStatusInterval) {
                  clearInterval(that.data.checkPayStatusInterval);
                }
              }
            })


          }
        })

      })

    });

  },
  loginAuth: function (phone, pcode) {
    var that = this;
    var nophone = app.getUserLoginNoPhone();
    if (nophone == 2) {
      console.log("已登录成功");
      return;
    }
    //调用登录接口
    wx.login({
      success: function (res) {
        console.log("wxLogin-------------")
        console.log(res);
        if (res.code) {


          //发起网络请求
          wx.request({
            url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/auth/login',
            header: {
              'content-type': 'application/x-www-form-urlencoded',
            },
            method: 'post',
            data: {
              code: res.code,
              phone: phone,
              pcode: pcode
            },
            success: function (res) {
              let netErr = app.handleRes(res, that);
              if (netErr) {
                return
              }
              var result = res.data.result;
              if (result == 0) {
                try {
                  wx.setStorageSync('pass', res.data.data.pass);
                  wx.setStorageSync('temp', res.data.data.temp);
                  wx.setStorageSync('ltime', res.data.data.ltime);
                  wx.setStorageSync('cpass', res.data.data.cpass);
                  wx.setStorageSync('uuid', res.data.data.uuid);
                  wx.setStorageSync('nophone', res.data.data.nophone);
                  wx.setStorageSync('isGetUserPhone', res.data.data.adminUserPhone);
                  wx.setStorageSync('user_id', res.data.data.uid);
                  app.globalData.loginData = res.data.data;

                  that.setData({
                    user_id: res.data.data.uid
                  })
                  if (res.data.data.adminUserPhone == 1) {
                    // that.setData({
                    //   messageBtnFlg: true
                    // });
                  }

                  var nophone = res.data.data.nophone;
                  if (nophone == null || nophone == undefined || nophone == 1) {
                    that.setData({
                      phoneAuthStatus: true,
                      phoneAuthBtt: 'scan'
                    });
                    return
                  } else if (nophone == 2) {
                    that.setData({
                      phoneAuthStatus: false,
                      phoneAuthBtt: ''
                    });
                    // that.getApageLeaseRecord()
                  }

                } catch (e) {}

              } else {
                if (result == 2) {
                  console.log("-------->去登陆")
                  that.data.loginStatus = true
                  that.data.scanStatus = false
                } else {
                  console.log("login error " + result)
                  that.setData({
                    alertBoxStatus: true,
                    alertBoxTipContent: res.data.description,
                    alertBoxBtnName: '确 定'
                  })
                }
              }

              //login 重新获取地图组件展示
              that.getShowControlsInfo()
              that.getRightBtns()
            }
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
          that.setData({
            alertBoxStatus: true,
            alertBoxTipContent: '登录失败',
            alertBoxBtnName: '确 定'
          })
        }
      }
    });
    // }
  },
  changePass: function () {
    var that = this;
    var timestamp = Date.parse(new Date());
    var ltime = app.getUserLoginTime();
    if (ltime != null && ltime != undefined) {
      var diff = timestamp - ltime
      let timeoutLen = 3 * 24 * 60 * 60 * 1000;
      if (diff <= 0 || diff > timeoutLen) {
        console.log("进行changePass")
      } else {
        if (app.globalData.loginFlag && app.globalData.wxScan.qrc) {
          that.getDevIdAndConnect(app.globalData.wxScan.qrc, 'scan')
        }
        app.globalData.loginFlag = ''
        console.log("可不进行changePass", app.globalData.loginFlag, app.globalData.wxScan.qrc)
        return
      }
    }

    app.executeRequest(function (header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/auth/cpass',
        method: 'post',
        header: header,
        data: {
          cpass: wx.getStorageSync('cpass'),
          uuid: wx.getStorageSync('uuid'),
          oldPass: app.getUserLoginPass()
        },
        success: function (res) {
          let netErr = app.handleRes(res, that);
          console.log('netErr', netErr, res);
          if (netErr) {
            return
          }
          if (res.data.result == 0) {
            wx.setStorageSync('pass', res.data.data.pass);
            wx.setStorageSync('temp', res.data.data.temp);
            wx.setStorageSync('ltime', res.data.data.ltime);
            app.globalData.loginData = res.data.data;
            if (res.data.data.uid) {
              wx.setStorageSync('user_id', res.data.data.uid);
              that.setData({
                user_id: res.data.data.uid
              })
            }
          } else {
            that.setData({
              phoneAuthStatus: true,
              phoneAuthBtt: 'scan',
              loading_show: false
            });
            wx.showToast({
              title: '请先登录',
              icon: 'none'
            })
          }
        }
      })

    })

  },
  closePhoneAuthStatus: function (e) {
    this.setData({
      phoneAuthStatus: false
    })
  },
  toViewLeaseProtocol: function () {
    wx.navigateTo({
      url: '../../../../pkgBak/pages/help/lease/lease',
    })
  },
  /**
   * 获取用户手机号
   */
  getPhoneNumber: function (e) {
    var that = this;

    that.recordBlueConnectError(ConstantData.err_type.log_click_login_btn, '点击登录按钮:' + e.detail.errMsg);

    if (e.detail.errMsg.indexOf('user deny') != -1) {
      return;
    } else {
      wx.showLoading({
        title: '登录中...',
      });
      //解密数据并登录成功
      app.executeRequest(function (header) {

        wx.request({
          url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/auth/wxPhoneAuthLogin',
          method: 'post',
          header: header,
          data: {
            iv: encodeURIComponent(e.detail.iv),
            encryptedData: encodeURIComponent(e.detail.encryptedData)
          },
          success: function (res) {
            getApp().hideLoading();
            console.log('getPhoneNumber--res', res);
            let netErr = app.handleRes(res, that);
            if (netErr) {
              return
            }
            if (res.data.result === 0) {
              //登录成功
              wx.showToast({
                title: '登录成功',
              });
              var btt = that.data.phoneAuthBtt;

              wx.setStorageSync('nophone', '2');
              wx.setStorageSync('iphone', res.data.phone)
              app.globalData.loginData.nophone = 2;
              app.globalData.pass = true
              that.setData({
                user_id: res.data.uid ? res.data.uid : '',
                phoneAuthStatus: false,
                phoneAuthBtt: ''
              })
              //   if (btt == 'scan') {
              //     let qrc = app.globalData.wxScan.qrc;
              //     if (qrc) {
              //       console.warn('登录成功直接连接');
              //       that.getDevIdAndConnect(qrc, 'login');
              //     } else {
              //       console.warn('登录成功调起摄像头');
              //       that.scan();
              //     }
              //   } else

              if (btt == 'record_user_deposit') {
                wx.navigateTo({
                  url: '../user_record/deposit/user_deposit',
                })
              } else if (btt == 'outpatient_add_employer') {
                //爱心租赁
                wx.navigateTo({
                  url: '../../pkgBak/pages/outpatient_service/manage_employer/manage_employer',
                })
              } else if (btt == 'outpatient_manage_careworker') {
                //门诊爱心租赁护工管理
                wx.navigateTo({
                  url: '../../pkgBak/pages/outpatient_service/manage_careworker/manage_careworker',
                })
              } else if (btt == 'deposit_record') {
                //押金记录
                wx.navigateTo({
                  url: '../user_record/deposit/user_deposit',
                })
              } else if (btt == 'no_return_blue_timeout') {
                //押金记录
                let desc = wx.getStorageSync("alertBoxTipContent");
                that.setData({
                  alertBoxStatus: true,
                  alertBoxTipContent: desc,
                  alertBoxBtnName: "确 定"
                })
              } else if (btt == 'manager_hospitallist') {
                wx.navigateTo({
                  url: '../../pkgBak/pages/manager/hospitallist/hospitallist',
                })
              } else if (btt == 'opt_user_admin_menus') {
                wx.navigateTo({
                  url: '../../pkgBak/pages/opt_user_admin/menus/menus',
                })
              } else if (btt == 'user_phone_code') {
                wx.navigateTo({
                  url: '../../pkgBak/pages/help/user_phone_coce/user_phone_code',
                })
              } else {
                wx.reLaunch({
                  url: '../index/index',
                })
              }

            } else if (res.data.result === 4) {
              wx.showToast({
                title: res.data.description,
                icon: "none"
              });
            } else {
              that.setData({
                phoneAuthStatus: true,
                phoneAuthBtt: 'scan',
                loading_show: false
              });
              wx.showToast({
                title: '请先登录',
                icon: 'none'
              })
            }
          },
          fail: function (err) {
            getApp().hideLoading();
          }
        });

      });
    }
  },

  clickCheckbox: function () {
    if (this.data.checkboxStatus == 'checkboxSelected') {
      this.setData({
        checkboxStatus: 'checkboxNoSelect',
        checkboxImg: "checkboxNoSelect.png"
      })
    } else {
      this.setData({
        checkboxStatus: 'checkboxSelected',
        checkboxImg: "checkboxSelected.png"
      })
    }
  },
  /**
   * 打开权限设置
   */
  openSetting: function () {
    let that = this;
    wx.openSetting({
      complete(res) {
        console.warn('【-蓝牙直连-openSetting】', res);
        if (res.authSetting['scope.userLocation']) {
          that.setData({
            loading_show: true,
            loading_desc: '权限已打开,开始连接...'
          })
          app.globalData.isDirectConnect = true;
          that.recordBlueConnectError(40010, 'directConnect start:openSetting success');
          BLELocker.directConnect(that.data.blueName, function (status, data) {
            that.handleStatus(status, data)
          }, 0, false, null, null, that);
        } else {}
      }
    })
  },

  start85Timer: function () {
    let that = this;
    that.clear85Timer();
    that.setData({
      openLockLeftSeconds: 20
    })
    that.data.timer_85_seconds = setInterval(() => {
      if (!app.globalData.devConnected && that.data.isRetry85) {
        that.setData({
          openning_show: false
        })
        //蓝牙断开
        that.clear85Timer();
        BLELocker.stop85Back1Timeout();
        BLELocker.stop85Back2Timeout();
        //重试开锁
        that.retry85('auto');
      } else if (that.data.openLockLeftSeconds == 0) {
        let pile_id = that.data.pile_id ? 'Z' + that.data.pile_id : '';
        let descMini = pile_id + '-' + ConstantData.err_type.data_85_send_timeout;
        statistic.noEjectDialog(that, descMini);
        that.recordBlueConnectError(ConstantData.err_type.data_85_timer, '20秒的85计时器计时结束，弹出未弹出提示')
        return
      }
      that.setData({
        openLockLeftSeconds: that.data.openLockLeftSeconds - 1
      })
    }, 1000)
  },
  /*开锁成功之后的回调*/
  clear85Timer: function () {
    let that = this;
    clearInterval(that.data.timer_85_seconds);
    that.data.timer_85_seconds = null;
  },
  sucOpenConfirm: function () {
    let that = this;
    that.hideModal1();
    that.data.openLockStat = false; //当前已开锁完毕
    that.data.hasOrderFlg = false;
    if (!that.data.equId || !that.data.opentime) {
      that.data.equId = wx.getStorageSync('equId');
      that.data.opentime = wx.getStorageSync('opentime');
    }
    that.registerAudioContexted();
    wx.navigateTo({
      url: 'lease_tip/lease_tip?pt=lease&equId=' + that.data.equId + "&opentime=" + that.data.opentime + '&lockType=' + that.data.lockType,
    })
  },
  registerAudioContext: function () {
    console.log('我是语音播报')
    this.innerAudioContext = wx.createInnerAudioContext();
    if (wx.getStorageSync('no_pay_deposit') && wx.getStorageSync('no_pay_deposit') == '1') {
      var voicePath = this.data.duanyuyin;
      this.setData({
        showTitle: false
      })
    } else {
      var voicePath = this.data.voiceTempFilePath;
      this.setData({
        showTitle: true
      })
    }
    this.innerAudioContext.src = voicePath;

    this.innerAudioContext.play();

    this.innerAudioContext.onEnded((res) => {
      console.log('播放结束了!');
    })

    this.innerAudioContext.onError((res) => {
      console.log('播放音频失败' + res);
    })

    this.innerAudioContext.onStop((res) => {
      console.log('停止播放!');
    })

  },
  // 租借播报
  registerAudioContexted: function () {
    var voicePath = this.data.yuyinzujie;
    if (this.data.lockType && this.data.voiceTempFilePath) {
      voicePath = this.data.voiceTempFilePath;
    }
    console.log("租借播报语音->", voicePath);
    this.innerAudioContext = wx.createInnerAudioContext();
    this.innerAudioContext.src = voicePath;

    this.innerAudioContext.play();

    this.innerAudioContext.onEnded((res) => {
      console.log('播放结束!');
    })

    this.innerAudioContext.onError((res) => {
      console.log('播放音频失败' + res);
    })

    this.innerAudioContext.onStop((res) => {
      console.log('停止播放!');
    })

  },
  retry85: function (retryType) {
    var that = this;
    that.hideModal1();
    that.setData({
      loading_show: true,
      loading_desc: '准备开锁...'
    })
    that.data.canRetry85 = true;
    that.data.hasOrderFlg = false;
    that.data.no_eject_back_flg = null;
    that.data.retryType85 = retryType;
    if (retryType == 'auto') {
      let desc = app.globalData.devConnected ? "蓝牙未断开,开锁失败,重试开锁" : "开锁时蓝牙断开，自动重新连接开锁";
      that.recordBlueConnectError(ConstantData.err_type.data_85_discon_retry, desc);
    } else {
      let desc = app.globalData.devConnected ? "蓝牙未断开,开锁失败,点击重试开锁" : "开锁时蓝牙断开，用户点击重试租借，重新连接";
      that.recordBlueConnectError(ConstantData.err_type.data_85_retry, desc);
    }
    that.clear85Timer();
    BLELocker.stop85Back1Timeout();
    BLELocker.stop85Back2Timeout();
    if (app.globalData.devConnected) {
      that.recordBlueConnectError(ConstantData.err_type.data_85_send, '开始发送85重试:' + app.globalData.devConnected);
      BLELocker.send85Command();
    } else {
      setTimeout(() => {
        connectCurrentBlue(that);
      }, 800)
    }
  },

  send85Command: function () {
    var that = this
    that.data.openLockLeaseOptStatus = false;
    that.setData({
      loading_show: false,
      openning_show: true,
      openning_desc: '设备正在开锁',
      openLockStat: true
    })
    let connected = getApp().globalData.devConnected;

    if (app.globalData.conBlueVer && app.globalData.conBlueVer == 'om-phy-1.0') {
      that.recordBlueConnectError(ConstantData.err_type.data_76_send, '开始发送phy开锁:' + connected);
      //one more 陪护椅锁开锁指令
      BLELocker.oneMorePhyBleUnlock();
      return;
    }

    if (that.data.isColonyCon) {
      console.log("蓝牙网关开锁处理---->");
      //蓝牙集群连接的
      colonyBlue.openLock(that.data.mac, that);
      that.data.isColonyCon = false;
      return;
    }

    if (that.data.lockSelTypeData) {
      that.recordBlueConnectError(ConstantData.err_type.data_76_send, '开始发送76:' + connected);

      //TODO 发送直行锁命令
      let doorNumArr = that.data.lockSelTypeData.selDoorNumSet;
      if (!doorNumArr || doorNumArr.length == 0) {
        that.recordBlueConnectError(ConstantData.err_type.data_76_fail, "门号信息为空")
      } else {
        that.data.lockSelTypeData = null;
        that.send76Command(doorNumArr[0]);
      }
      return;
    }
    that.recordBlueConnectError(ConstantData.err_type.data_85_send, '开始发送85:' + app.globalData.devConnected);
    //是否正在开锁中
    app.globalData.isOpenLock = true;
    setTimeout(function () {
      that.start85Timer();
      BLELocker.send85Command(function (isSuccess) {
        if (isSuccess == false) {
          that.clear85Timer();
          //重试开锁
          that.retry85('auto');
          let failDesc = app.globalData.devConnected + ";retry85Auto:" + that.data.rfId;
          that.recordBlueConnectError(ConstantData.err_type.data_85_send_fail, (that.data.isRedirectOpenLockFlg ? "redirect:" : "开始开锁-fail") + failDesc);
        } else {
          that.recordBlueConnectError(ConstantData.err_type.data_85_send_suc, (that.data.isRedirectOpenLockFlg ? "redirect:" : "开始开锁-suc") + that.data.rfId)
        }
      })
    }, 500);


  },
  send75Command: function (params) {
    var that = this;
    //发送75命令获取信息
    BLELocker.send75Command(function (isSuccess) {
      if (isSuccess == false) {
        if (params == '00') {
          that.connectBLEDevice(that.data.curBlueName)
        } else {
          wx.showModal({
            showCancel: false,
            title: '温馨提示',
            content: '通信失败,请扫码重试',
            success(res) {}
          })
        }
      } else if (isSuccess == "recevieTimeout") {
        that.handleStatus(BLELocker.Status.bleRecive75Timeout);
      }
    }, params);
  },
  //发送执行锁开锁命令
  send76Command: function (doorNum) {
    var that = this;
    doorNum = doorNum.toString(16);
    let openDoorNum = doorNum.length == 1 ? '0' + doorNum : doorNum;
    //请求成功
    BLELocker.send76Command(function (isSuccess) {
      if (isSuccess == false) {
        that.setData({
          loading_show: false,
          modal: {
            modal_show: true,
            desc: '格子柜开门失败:' + ConstantData.err_type.data_76_fail,
            confirm: true
          }
        })
        that.recordBlueConnectError(ConstantData.err_type.data_76_fail, 'mac=' + mac + ';res:' + JSON.stringify(res));
      }

    }, openDoorNum)
  },
  send95Command: function () {
    var that = this;
    //重试发送95的标记
    that.data.retry95Flg = true;
    if (!that.data.randomNum) {
      that.data.randomNum = app.globalData.boxRandomNumKey;
    }
    if (!getApp().globalData.devConnected) {
      that.handleConDevRes()
    } else if (that.data.randomNum) {
      BLELocker.send95Command(function (isSuccess) {
        if (isSuccess == false) {
          that.connectBLEDevice(that.data.curBlueName)
        } else if (isSuccess == "recevieTimeout") {
          that.handleStatus(BLELocker.Status.bleRecive95Timeout);
        }
      })
      return;
    } else {
      that.setData({
        modal: {
          modal_show: false
        }
      })
    }
  },

  send98Command: function (version) {

    if (version != null && version != undefined) {
      var arr = version.split(".");
      var ver = arr[arr.length - 1];
      var vInt = parseInt(ver);
      if (vInt >= 190510) {
        console.log("--发送98数据------->")
        BLELocker.send98Command(function (isSuccess) {
          console.log("98是否发送成功:", isSuccess);
        })
      }
    }

  },

  //处理设备连接状态变化回调
  handleStatus: function (status, data) {
    var that = this
    console.log('我就是_Callback', status, data)
    if (!that || !that.data) {
      return
    }
    let pile_id = that.data.pile_id ? 'Z' + that.data.pile_id : '';
    if (status == BLELocker.Status.ble01Data) {
      console.log("---新固件驱动连接成功...", data);
      that.setData({
        openning_show: false,
        connectDesc: "连接成功,数读取中...",
        loading_show: true,
        loading_desc: '数据读取中',
      });
      //新固件会主动上报95数据
    } else if (status == BLELocker.Status.bleScanStart) {
      that.setData({
        connectDesc: "查找设备中,请稍后...",
        loading_desc: '查找设备中,请稍后...',
      });
    } else if (status == BLELocker.Status.appVersionNotSupported) {
      getApp().hideLoading()

      //1.关闭正在连接的提示对话框 2.弹出提示用户APP版本太低不支持的对话框
      that.setData({
        loading_show: false,
        alertBoxStatus: true,
        alertBoxTipContent: "微信APP版本太低不支持",
        alertBoxBtnName: "确 定"
      })
    } else if (status == BLELocker.Status.bleIsClosed) {
      getApp().hideLoading()
      let systemInfo = wx.getStorageSync('systeminfo');
      if (systemInfo.system && systemInfo.system.toLowerCase().indexOf('ios 13') != -1) {
        that.setData({
          openning_show: false,
          loading_show: false,
          modal: {
            modal_show: true,
            icon_name: 'icon-lanya',
            desc: '请在系统设置中打开微信的蓝牙权限后重试',
            desc_center: true,
            desc_mini: 'BT权限不成功' + pile_id + '(' + that.data.phoneInfo + '-100310)',
            open_ble_auth_show: true,
          }
        })
        that.recordBlueConnectError(100310, "modalErr:ios13-蓝牙未打开");
      } else {
        that.setData({
          openning_show: false,
          loading_show: false,
          modal: {
            modal_show: true,
            desc_mini: 'BT未打开' + pile_id + '（' + that.data.phoneInfo + '-100311)',
            desc: '请打开蓝牙后重试', //此处的文字在wxml页面有用到，如果变更的话wxml也要同步变更
            retryConnect: true
          }
        })
        that.recordBlueConnectError(100311, "modalErr:蓝牙未打开");
      }
    } else if (status == BLELocker.Status.adaperOpenFail) {
      getApp().hideLoading()
      wx.stopBluetoothDevicesDiscovery({
        success: function (e) {
          console.log(e);
        },
        complete: function (i) {
          console.log(i);
        }
      });
      wx.closeBLEConnection({
        deviceId: that.data.wxDeviceId,
        success: function (res) {
          console.log("close suc", res)
        },
        fail: function (res) {
          console.log("close err", res);
        }
      });
      wx.closeBluetoothAdapter({
        success: function (res) {
          console.log("closeA suc", res)
        },
        fail: function (res) {
          console.log("closeA err", res);
        }
      })
      if (that.data.curIsDirectCon) {
        app.globalData.isDirectConnect = true;
        that.setData({
          loading_desc: '正在自动重连...'
        })
        console.warn('连接失败,正在自动重连');
        BLELocker.directConnect(that.data.blueName, function (status1, data1) {
          that.handleStatus(status1, data1)
        }, 0, false, null, null, that);
        that.recordBlueConnectError(40010, 'directConnect start-adaperOpenFail:' + app.globalData.conErrDesc);
      } else {
        app.globalData.isDirectConnect = false;
        that.setData({
          openning_show: false,
          loading_show: false,
          modal: {
            modal_show: true,
            desc_mini: 'BT调起不成功' + pile_id + '（' + that.data.phoneInfo + '-100312)',
            desc: '请关闭蓝牙再打开后重试',
            retryConnect: true
          }
        })
        that.recordBlueConnectError(100312, "modalErr:初始化蓝牙适配器失败");
      }

    } else if (status == BLELocker.Status.bleNotSupportWXService || status == BLELocker.Status.bleNotSupportWXCharacteristic) {
      getApp().hideLoading()

      //1.关闭正在连接的提示对话框 2.弹出提示用户扫描的设备不支持微信协议（其实就是扫描了不支持微信协议连接的设备）
      that.setData({
        loading_show: false,
        alertBoxStatus: true,
        alertBoxTipContent: "系统版本低,可能无法完成租赁",
        alertBoxBtnName: "确 定"
      })
    } else if (status == BLELocker.Status.bleReceiveAuthData) {
      getApp().hideLoading()

      //1.将正在连接的提示对话框中的提示语,变更为：连接成功,读取数据中,提示语请自行修改,这个时候正在发送95指令
      that.setData({
        loading_desc: "连接成功,数据读取中",
        loading_show: true
      });

    } else if (status == BLELocker.Status.bleConnectTimeout) {
      getApp().hideLoading()
      wx.stopBluetoothDevicesDiscovery({
        success: function (e) {
          console.log(e);
        },
        complete: function (i) {
          console.log(i);
        }
      });
      wx.closeBLEConnection({
        deviceId: that.data.wxDeviceId,
        success: function (res) {
          console.log("close suc", res)
        },
        fail: function (res) {
          console.log("close err", res);
        }
      });
      wx.closeBluetoothAdapter({
        success: function (res) {
          console.log("closeA suc", res)
        },
        fail: function (res) {
          console.log("closeA err", res);
        }
      })
      var errCode = getTimeoutReasonCode(that);
      if (that.data.curIsDirectCon) {
        app.globalData.isDirectConnect = true;
        that.setData({
          loading_desc: '正在自动重连...'
        })
        console.warn('连接失败,正在自动重连');
        BLELocker.directConnect(that.data.blueName, function (status1, data1) {
          that.handleStatus(status1, data1)
        }, 0, false, null, null, that);
        that.recordBlueConnectError(40010, 'directConnect start-bleConnectTimeout:' + app.globalData.conErrDesc);
        return;
      }
      app.globalData.isDirectConnect = false;
      that.recordBlueConnectError(20003, "connect timeout:" + app.globalData.conErrDesc);

      //标记存储蓝牙连接失败的 时间
      colonyBlue.bleConFailMark();
      //1.关闭正在连接的提示对话框 2.弹出提示用户连接设备超时,重新扫码
      that.setData({
        loading_show: false,
        openning_show: false,
      })

      console.log('监听到bleConnectTimeout', errCode);

      if (errCode == '10039') {
        that.setData({
          modal: {
            modal_show: true,
            desc: '请关闭蓝牙再打开后重试',
            desc_mini: 'receiveData不成功' + pile_id + '(' + that.data.phoneInfo + '-10039)',
            retryConnect: true
          }
        })
        that.recordBlueConnectError(10039, 'modalErr:接收数据时超时或报错');
      } else if (errCode == '100310') {
        that.setData({
          modal: {
            modal_show: true,
            icon_name: 'icon-lanya',
            desc: '请在系统设置中打开微信的蓝牙权限后重试',
            desc_center: true,
            desc_mini: 'BT权限不成功' + pile_id + '(' + that.data.phoneInfo + '-100310)',
            open_ble_auth_show: true,
          }
        })
        that.recordBlueConnectError(100310, 'modalErr:ios13-蓝牙未打开');
      } else if (errCode.indexOf('10034') != -1) {
        getBLETimeoutReasonType(that);
      } else {
        that.setData({
          modal: {
            modal_show: true,
            desc: "请关闭蓝牙再打开后重试",
            icon_name: 'icon-lanya',
            desc_mini: 'BT调起不成功' + pile_id + '(' + that.data.phoneInfo + '-' + errCode + ')',
            desc_center: true,
            retryConnect: true
          }
        })
        that.recordBlueConnectError(errCode, 'modalErr:连接超时');
      }

      app.sendLog();
    } else if (status == BLELocker.Status.bleClosed) {
      getApp().hideLoading()

      //1.关闭正在连接的提示对话框（如果当前不是正在连接,是已经弹出租凭开锁对话框,则可以关闭租凭开锁对话框） 2.弹出提示用户蓝牙关闭,请重新扫码
      if (that.data.showModalStatus) {
        that.setData({
          showModalStatus: false,
          mapShowStatus: true,
        })
      }
      //1.关闭正在连接的提示对话框 2.弹出提示用户手机蓝牙未打开
      that.setData({
        openning_show: false,
        loading_show: false,
        modal: {
          modal_show: true,
          desc: '蓝牙已关闭,重新打开扫码重试',
          confirm: true
        }
      })
    } else if (status == BLELocker.Status.bleOpened) {
      getApp().hideLoading()
      // wx.showToast({
      //   title: '手动打开蓝牙',
      // })

      //这里不需要做任何处理

    } else if (status == BLELocker.Status.bleSend85Timeout) { //暂未开启
      getApp().hideLoading()
      // wx.showToast({
      //   title: '发送85超时',
      // })

      //1.关闭租凭开锁提示对话框 2.提示用户开锁超时,请重新扫码
      that.setData({
        showModalStatus: false,
        loading_show: false,
        mapShowStatus: true,
        openning_show: false,
        openLockLeaseOptStatus: true,
        modal: {
          modal_show: true,
          desc: '开锁超时,扫码归还后重试',
          desc_mini: 'send85Timeout' + pile_id + '-' + ConstantData.err_type.data_85_send_timeout,
          comfirm: true
        },
      });
      that.clear85Timer();
      that.recordBlueConnectError(ConstantData.err_type.data_85_send_timeout, 'modalErr:发送85超时' + ":" + app.globalData.devConnected);
    } else if (status == BLELocker.Status.ble85Back1Timeout) {
      getApp().hideLoading()
      app.globalData.isOpenLock = false;
      app.globalData.isConnecting = false;
      that.data.openLockStat = false; //当前已开锁完毕
      that.recordBlueConnectError(ConstantData.err_type.data_85_back1_timeout, "85第1次回执超时,设备:mac=" + that.data.mac + ":" + app.globalData.devConnected)
      if (!app.globalData.devConnected) {
        that.clear85Timer();
        //重试开锁
        that.retry85('auto');
      } else if (that.data.hasOrderFlg && that.data.no_eject_flg || that.data.no_eject_back_flg == 1 || that.data.no_eject_flg) {
        let descMini = pile_id + '-' + ConstantData.err_type.data_85_back1_timeout_noeject_inner;
        statistic.noEjectDialog(that, descMini);
        that.recordBlueConnectError(ConstantData.err_type.data_85_back1_timeout_noeject_inner, '85第一条回执超时，显示“未弹出弹框”');
      } else {
        let descMini = '85backTimeout' + pile_id + '-' + ConstantData.err_type.data_85_back1_timeout_else;
        statistic.noEjectDialog(that, descMini);
        that.recordBlueConnectError(ConstantData.err_type.data_85_back1_timeout_else, 'modalErr:85第一条回执超时,请扫码归还后重试');
      }
      app.sendLog();
    } else if (status == BLELocker.Status.ble85Back2Timeout) {
      getApp().hideLoading()

      that.recordBlueConnectError(ConstantData.err_type.data_85_back2_timeout, "85第2次回执超时,显示“未弹出弹框”,设备mac=" + that.data.mac)
      that.data.openLockStat = false; //当前已开锁完毕
      app.globalData.isOpenLock = false;
      app.globalData.isConnecting = false;
      let descMini = pile_id + '-' + ConstantData.err_type.data_85_back2_timeout_noeject_inner;
      statistic.noEjectDialog(that, descMini);

    } else if (status == BLELocker.Status.bleSend95Timeout) {
      getApp().hideLoading()
      if (that.data.curBlueName && that.data.timeout95RetryFlg) {
        that.data.timeout95RetryFlg = false;
        that.data.retryCon = false; //刚开始还没有进行重试点击
        that.recordBlueConnectError(ConstantData.err_type.new_conf_95_timeout, '95发送超时,重新连接');
        //收到超时后，重置参数及关闭适配器等需要时间
        setTimeout(function () {
          that.connectBLEDevice(that.data.curBlueName);
        }, 250);
        return;
      }

      //标记存储蓝牙连接失败的 时间
      colonyBlue.bleConFailMark();
      //1.关闭正在连接的提示对话框 2.弹出提示用户连接设备失败,重新扫码
      that.setData({
        showModalStatus: false,
        mapShowStatus: true,
        loading_show: false,
        modal: {
          modal_show: true,
          desc_mini: '95超时' + pile_id + '-' + ConstantData.err_type.data_95_send_timeout,
          desc: '连接失败,扫码重试',
          confirm: true
        }
      })

      that.recordBlueConnectError(ConstantData.err_type.data_95_send_timeout, 'modalErr:95超时');
      app.sendLog();
    } else if (status == BLELocker.Status.bleRecive95Timeout || status == BLELocker.Status.bleReciveAuto95Timeout) {

      //标记存储蓝牙连接失败的 时间
      colonyBlue.bleConFailMark();
      //1.关闭正在连接的提示对话框 2.弹出提示用户连接设备失败,重新扫码
      that.setData({
        showModalStatus: false,
        mapShowStatus: true,
        loading_show: false,
        modal: {
          modal_show: true,
          desc_mini: '95接收超时' + pile_id + '-' + ConstantData.err_type.new_conf_95_receive_timeout,
          desc: '连接失败,扫码重试',
          confirm: true
        }
      })

      that.recordBlueConnectError(ConstantData.err_type.new_conf_95_receive_timeout, '95数据超时:' + status);

    } else if (status == BLELocker.Status.ble85Data || status == BLELocker.Status.ble88Data) {
      that.data.isRetry85 = false;
      app.globalData.isOpenLock = false;
      //开锁完成隐藏可关闭蓝牙
      app.globalData.isConnecting = false;
      //隐藏可以关闭蓝牙
      that.data.hideIsDisconnectStat = true;
      that.recordBlueConnectError(ConstantData.err_type.data_85_suc, "85回执data-" + JSON.stringify(data))
      console.warn('---收到85', data);

      if (that.data.blankPileOpenFlg) {
        //非空桩开锁的可以跳转到开锁结果提示页面
        console.log("空桩开锁完成，不进行跳转")
        return;
      }
      //191101及之后的驱动
      if (data) {
        if (data.backSeq == 1 && !data.resultEnum) {
          //控制盒收到开锁命令
          that.data.openLockStat = true; //当前正在开锁
        } else if (data.backSeq == 2) {
          that.setData({
            openning_show: false
          })
          //开锁结束
          that.clear85Timer();
          BLELocker.stop85Back1Timeout();
          BLELocker.stop85Back2Timeout();

          that.data.openLockStat = false; //当前开锁结束
          if (data.noEject == 1) { //设备未弹出
            let descMini = pile_id + '-' + ConstantData.err_type.data_85_back2_noeject_inner;
            statistic.noEjectDialog(that, descMini);
            that.recordBlueConnectError(ConstantData.err_type.data_85_back2_noeject_inner, '85第二条回执提示未弹出，显示“未弹出弹框”');
          } else {
            console.log("开锁后断开蓝牙--ccc->")
            app.globalData.isConnecting = false;
            BLELocker.disconnect('index3456')

            setTimeout(() => {
              that.setData({
                openning_show: false
              })
            }, 2000)
            if (!that.data.equId || !that.data.opentime) {
              that.data.equId = wx.getStorageSync('equId');
              that.data.opentime = wx.getStorageSync('opentime');
            }

            that.registerAudioContexted();
            wx.navigateTo({
              url: 'lease_tip/lease_tip?pt=lease&equId=' + that.data.equId + "&opentime=" + that.data.opentime + '&lockType=' + that.data.lockType,
            })
          }

        } else {
          console.log('UI层收到85数据', data)
          that.data.openLockStat = false; //当前开锁结束
          that.setData({
            loading_show: false,
            showModalStatus: false,
            mapShowStatus: true,
            isBackChairStatus: true,
          });
          setTimeout(() => {
            that.setData({
              openning_show: false
            })
          }, 3000)

          if (!that.data.equId || !that.data.opentime) {
            that.data.equId = wx.getStorageSync('equId');
            that.data.opentime = wx.getStorageSync('opentime');
          }

          that.registerAudioContexted();
          wx.navigateTo({
            url: 'lease_tip/lease_tip?pt=lease&equId=' + that.data.equId + "&opentime=" + that.data.opentime + '&lockType=' + that.data.lockType,
          })

        }
      } else {
        that.data.openLockStat = false; //当前开锁结束
        if (that.data.hasOrderFlg && that.data.no_eject_flg || that.data.no_eject_back_flg == 1) {
          let descMini = pile_id + '-' + ConstantData.err_type.data_85_null_inner;
          statistic.noEjectDialog(that, descMini);
          that.recordBlueConnectError(ConstantData.err_type.data_85_null_inner, '85回执为空，显示“未弹出弹框”');
        } else {
          //1.关闭租凭开锁提示对话框 2.提示用户开锁失败,请重新扫码
          that.setData({
            showModalStatus: false,
            loading_show: false,
            mapShowStatus: true,
            openning_show: false,
            openLockLeaseOptStatus: true,
            modal: {
              modal_show: true,
              desc: '开锁失败,扫码归还后重试',
              desc_mini: '85null' + pile_id + '-' + ConstantData.err_type.data_85_null_else,
              comfirm: true
            },
          })
          that.recordBlueConnectError(ConstantData.err_type.data_85_null_else, 'modalErr:85null');
          app.sendLog();
        }
      }

    } else if (status == BLELocker.Status.ble95Data) {
      wx.removeStorageSync('retryConCounts');
      app.globalData.conIsSuc = true;
      if (app.globalData.conTimeoutTimer) {
        clearTimeout(app.globalData.conTimeoutTimer);
      }
      if (app.globalData.data95ReceiveTimer) {
        clearTimeout(app.globalData.data95ReceiveTimer);
      }
      if (app.globalData.directConnectTimer) {
        clearTimeout(app.globalData.directConnectTimer);
      }
      if (app.globalData.auto95RecTimer) {
        clearTimeout(app.globalData.auto95RecTimer);
      }

      //设置全局的首页对象句柄，便于开锁85时进行调用
      console.warn('ble95Data---->', data);
      let conTimeLen = app.globalData.startConTime ? (new Date().getTime() - app.globalData.startConTime) : -1;
      let err95TypeVal = that.data.retry95Flg ? ConstantData.err_type.retry_send_95_log : ConstantData.err_type.receive_95_time;
      that.recordBlueConnectError(err95TypeVal, 'ble95Data:' + conTimeLen);
      //数据读取中
      if (that.data.curIsDirectCon && app.globalData.isDirectConnect) {
        that.recordBlueConnectError(40012, 'directConnect success');
      }
      let nowTime = new Date().getTime();

      //防止连续95数据 start
      if (that.data.data95Time && (nowTime - that.data.data95Time < that.data.many95DataInterval)) {
        console.log('操作频繁');
        that.data.data95Time = nowTime;
        that.recordBlueConnectError(ConstantData.err_type.data_95_repeat, '连续95数据,已忽略');
        return;
      }
      that.data.data95Time = nowTime;
      //防止连续95数据 end

      if (that.data.send85Time && (nowTime - that.data.send85Time < that.data.blue95Interval)) {
        console.log('操作频繁，忽略95数据');
        that.setData({
          loading_show: false
        })
        wx.showToast({
          title: '您的操作过于频繁，请稍候再试',
          icon: 'none'
        })
        return;
      }
      that.setData({
        connectDesc: "数据已返回,开始处理...",
        loading_show: true,
        loading_desc: '数据已返回,开始处理...',
      });
      if (data == null) {
        getApp().hideLoading()
        // wx.showToast({
        //   title: '发送95失败',
        // })

        //1.关闭正在连接的提示对话框 2.弹出提示用户连接设备失败,重新扫码
        that.setData({
          showModalStatus: false,
          mapShowStatus: true,
          loading_show: false,
          modal: {
            modal_show: true,
            desc_mini: '95null' + pile_id + '-' + ConstantData.err_type.data_95_null,
            desc: '连接失败,请扫码重试',
            confirm: true
          }
        })
        that.recordBlueConnectError(ConstantData.err_type.data_95_null, 'modalErr:95null');
        app.sendLog();
      } else {
        getApp().hideLoading()

        if (data.mac && that.data.conMac && data.mac != that.data.conMac) {
          that.recordBlueConnectError(ConstantData.err_type.data_95_no_lastest, '不是最新扫码95数据:' + data.mac + "," + that.data.conMac);
          return;
        }

        if (data.motorStat == 1) {
          that.setData({
            showModalStatus: false,
            mapShowStatus: true,
            loading_show: false,
            openning_show: false,
            modal: {
              modal_show: true,
              desc: '设备重启中，请稍候再试',
              desc_mini: pile_id + '-' + ConstantData.err_type.data_95_motorunning,
              confirm: true
            }
          });
          that.recordBlueConnectError(ConstantData.err_type.data_95_motorunning, "95马达状态motorStat-" + data.motorStat + '-rfid-' + data.rfid);
          return;
        }

        if (that.data.canRetry85) {
          //如果是三分钟之内，显示未弹出弹框
          console.warn('--未弹出，重新连接成功，发送85');
          if (that.data.retryType85 == 'auto') {
            that.recordBlueConnectError(ConstantData.err_type.data_95_85_retry_atuo, '自动重试租借，重新连接成功，开始发送85');
          } else {
            that.recordBlueConnectError(ConstantData.err_type.data_95_85_retry, '用户点击重试租借，重新连接成功，开始发送85');
          }
          that.data.canRetry85 = false;
          that.send85Command();
          return;
        }

        if (that.data.pileLocation != undefined && that.data.pileLocation != null) {
          data.location = that.data.pileLocation;
        }
        let version = BLELocker.getDriverVersion();
        if (!data.pile_ver) {
          data.pile_ver = version;
        }

        let sysInfo = wx.getStorageSync("systeminfo");
        data.phoneType = sysInfo.model;
        var electrict = data.electrict; //归位桩剩余电量
        let noEject = data.chairIsEjectLose;
        let no_eject_times = 0;
        if (noEject == 1) {
          no_eject_times = wx.getStorageSync('no_eject_times') || 1;
          wx.setStorageSync('no_eject_times', no_eject_times + 1)
        } else {
          wx.removeStorageSync('no_eject_times')
        }
        let user_no_back = wx.getStorageSync('user_no_back')
        console.log('no_eject_times============', no_eject_times, user_no_back)
        if (no_eject_times > 2 && !user_no_back) {
          that.setData({
            showModalStatus: false,
            mapShowStatus: true,
            loading_show: false,
            openning_show: false,
            modal: {
              modal_show: true,
              desc: '请换一台设备租赁',
              desc_mini: 'noEject' + pile_id + '-' + ConstantData.err_type.data_95_noeject,
              confirm: true
            }
          });
          that.recordBlueConnectError(ConstantData.err_type.data_95_noeject, "modalErr-mac=" + data.mac);
          return;
        }


        if (app.globalData.conBlueVer && app.globalData.conBlueVer == 'om-phy-1.0') {} else {
          //发送控制盒广播配置命令
          BLELocker.sendBroadcastConfCommand();
          if (that.data.isSend98Cmd) {
            setTimeout(function () {
              //发送98获取数据
              that.send98Command(version);
            }, 200);
          }
        }


        that.setData({
          elecInt: electrict,
          hookStatus: data.hookStatus,
          switchStatus: data.chairSwitchSatus,
          didiStat: data.programRestartTimes,
          // picTip: picTipDesc,
          mac: data.mac,
          rfid: data.rfid,
          rfidIsCache: data.rfidIsCache ? data.rfidIsCache : -100
        })
        var mac = data.mac;
        console.log("mac=" + mac + ",left electrit -->" + electrict)
        var rfId = data.rfid;
        var costTime = data.costTime;
        //存储控制盒上报的记录的时长
        that.data.conBoxCostTime = data.costTime;
        console.log("rfId=" + rfId + ",costTime=" + costTime)

        console.log("处理95指令接收的数据", data)
        let location = wx.getStorageSync('location')
        data.location = location
        that.data.static95Data = data;
        console.log("处理95指令接收的数据2", data)
        let dataType = "95data";
        statistic.statisticData(dataType, JSON.stringify(that.data.static95Data));

        that.data.blankPileOpenFlg = false;

        //空桩开锁权限判断,有空桩开锁权限且rfid不识别或rfid从缓存中读取的，可直接进行开锁
        let isBlankOpen = (data.rfidIsCache == 1 || 'FFFFFFFF' == rfId) && that.data.isNoRfidOpen == 1; //空桩开锁权限
        isBlankOpen = that.data.isNoRfidOpen == 2 || isBlankOpen; //存在辅助开锁权限的不做空桩判断可直接开锁20200805145400
        if (isBlankOpen) {
          wx.showLoading({
            title: '检测中..',
          });

          setTimeout(function () {
            getApp().hideLoading();
            if (that.data.isColonyCon) {
              colonyBlue.openLock(that.data.mac, that, 1);
            } else {
              that.data.blankPileOpenFlg = true;
              that.send85Command();
            }
            that.setData({
              loading_show: false,
              openning_show: false
            })
            wx.showToast({
              title: '开锁完成',
            })

          }, 2000);
        } else if ('FFFFFFFF' == rfId) { //轮椅未识别
          that.hideModal1();
          let rfid_error_time = wx.getStorageSync('rfid_error_time') || 1;
          wx.setStorageSync('rfid_error_time', rfid_error_time + 1);
          let errType = '';
          //第3次不识别
          if (rfid_error_time > 2) {
            //判断是否归还
            if (user_no_back) {
              errType = ConstantData.err_type.data_95_rfid_back_times;
              that.data.modal.desc = "请确认设备已经锁好且拉不下来后可联系客服帮您归还"
              that.data.modal.desc_mini = "rfid不识 " + pile_id + "-" + errType;
              that.data.modal.modal_show = true
              that.data.modal.contact = true
            } else {
              errType = ConstantData.err_type.data_95_rfid_rent_times;
              that.data.modal.desc = "请换一个设备租赁";
              that.data.modal.desc_mini = "rfid不识 " + pile_id + "-" + errType;
              that.data.modal.modal_show = true;
              that.data.modal.confirm = true;
            }
            BLELocker.disconnect('index4608', 'stopConnect');
          } else {
            that.data.modal.modal_show = true
            //判断是否归还
            if (user_no_back) {
              errType = ConstantData.err_type.data_95_rfid_back;
              that.data.modal.desc = '请将轮椅靠右摆放且听到滴滴两声后再点击重试。'
              if (that.data.pile_type) {
                that.data.modal.desc = '请将轮椅摆正。然后往里推着轮椅，听到滴滴两声后再点击重试。'
              }
              that.data.modal.desc_mini = "rfid不识 " + pile_id + "-" + errType;
              that.data.modal.retry95 = true
              that.data.modal.img1_show = true
            } else {
              if (data.chairSwitchSatus == 0) {
                errType = ConstantData.err_type.data_95_rfid_rent_noInsert;
                that.data.modal.desc = '当前桩上可能没有轮椅，请换一个有轮椅的桩扫码租赁。'
                that.data.modal.desc_mini = "rfid不识 inSwitch " + pile_id + "-" + errType;
                that.data.modal.confirm = true
                BLELocker.disconnect('index4628', 'stopConnect');
              } else {
                errType = ConstantData.err_type.data_95_rfid_rent;
                that.data.modal.desc = '请将轮椅左右摇晃并靠右摆放后点击重试'
                if (that.data.pile_type) {
                  that.data.modal.desc = '请将轮椅摆正。然后往里推着轮椅点击重试。'
                }
                that.data.modal.desc_mini = "rfid不识 " + pile_id + "-" + errType;
                that.data.modal.retry95 = true
                that.data.modal.img1_show = true
              }

            }
          }
          that.setData({
            loading_show: false,
            modal: that.data.modal,
          })
          if (errType) {
            that.recordBlueConnectError(errType, "modalErr:rfid不识别");
          }
        } else if ('00000000' == rfId && data.chairSwitchSatus == 0) { //共享陪护床
          if (user_no_back && wx.getStorageSync('user_no_back').data.noBack.lockType == '宜家锁') {
            that.data.modal.desc = "请确认设备已按照图示锁好后\n点击重试。"
            that.data.modal.desc_mini = "PHC inSwitch " + pile_id + "-" + ConstantData.err_type.data_95_phc;
            that.data.modal.modal_show = true
            that.data.modal.contact = true
            that.setData({
              showyijia: true
            })
          } else if (user_no_back && wx.getStorageSync('user_no_back').data.noBack.lockType != '宜家锁') {
            that.data.modal.desc = "请检查设备是否已经锁好\n如果已锁好，请联系客服帮您归还。"
            that.data.modal.desc_mini = "PHC inSwitch " + pile_id + "-" + ConstantData.err_type.data_95_phc;
            that.data.modal.modal_show = true
            that.data.modal.contact = true
          } else {
            that.data.modal.desc = "该设备故障，请更换一个设备使用！"
            that.data.modal.desc_mini = "PHC inSwitch " + pile_id + "-" + ConstantData.err_type.data_95_phc;
            that.data.modal.modal_show = true
            that.data.modal.confirm = true
          }
          that.setData({
            loading_show: false,
            modal: that.data.modal,
          })
          that.recordBlueConnectError(ConstantData.err_type.data_95_phc, "modalErr:陪护床插入开关错误");
        } else if (that.data.isJudgeInsertSwitch && that.data.isNoRfidOpen != 1 && data.chairSwitchSatus == 0 && user_no_back && data.programRestartTimes != 1) { //isJudgeInsertSwitch:判断插入开关;isNoRfidOpen:空桩开锁;
          BLELocker.disconnect('index4630', 'stopConnect');
          that.recordBlueConnectError(10060, '用户中断连接4630');
          that.hideModal1()
          //用户归还且插入状态不对
          let insert_fail_time = wx.getStorageSync('insert_fail_time') || 1;
          wx.setStorageSync('insert_fail_time', insert_fail_time + 1);
          let errType = '';
          //第3次
          if (insert_fail_time > 2) {
            errType = ConstantData.err_type.data_95_noInsert_times;
            that.data.modal.desc = "请确认设备已经锁好且拉不下来后可联系客服帮您归还。"
            that.data.modal.desc_mini = "inSwitch " + pile_id + "-" + errType;
            that.data.modal.modal_show = true
            that.data.modal.contact = true
          } else {
            errType = ConstantData.err_type.data_95_noInsert;
            that.data.modal.desc = "1、请检查设备是不是已经锁好\n2、如果已经锁住，请将轮椅摆正，然后往里推着轮椅点击重试。"
            that.data.modal.desc_mini = "inSwitch " + pile_id + "-" + errType;
            that.data.modal.modal_show = true
            that.data.modal.img2_show = true
            that.data.modal.retry95 = true
            that.data.modal.desc_center = false
          }
          that.setData({
            loading_show: false,
            modal: that.data.modal,
          })
          if (errType) {
            that.recordBlueConnectError(errType, "modalErr:插入开关错误");
          }
        } else {
          wx.removeStorageSync('rfid_error_time');
          wx.removeStorageSync('insert_fail_time');

          if (that.data.canceledConnect) {
            that.recordBlueConnectError(10061, "用户中断连接1");
            return;
          }
          that.openOrReturnEquitment(rfId, mac, costTime); //开锁或归还
        }
      }
    } else if (status == BLELocker.Status.ble75zeroData) {
      //75第0包数据
      console.log("接收到格子柜第0包数据", data, app.globalData.data75ReceiveTimer);
      if (app.globalData.data75ReceiveTimer) {
        clearTimeout(app.globalData.data75ReceiveTimer);
      }
      if (app.globalData.conTimeoutTimer) {
        clearTimeout(app.globalData.conTimeoutTimer);
        app.globalData.conTimeoutTimer = null;
      }
      //发送获取各个门的状态信息
      if (data) {
        that.setData({
          openning_show: false,
          connectDesc: "数读设备成功,读取格子状态中...",
          loading_show: true,
          loading_desc: '读取格子状态中01...',
        });
        that.data.latticeCabinetData = new Object();
        that.data.latticeCabinetData.latticeData = data;
        that.data.latticeCabinetData.doorDataList = new Array();
        let equStatData = data.equStat;
        let doorCount = parseInt(equStatData.maxDoorCount, 16);
        console.log("格子柜的在线门数量---->", doorCount, equStatData.maxDoorCount);

        that.data.data75NReceiveTimer = setTimeout(function () {
          console.log("75N包数据接收超时...", callback);
          that.handleStatus(BLELocker.Status.bleRecive75NTimeout);
        }, 8000);

        that.send75Command("01");
      } else {
        wx.showModal({
          showCancel: false,
          title: '温馨提示',
          content: '获取柜信息失败,请扫码重试',
          success(res) {}
        })
      }

    } else if (status == BLELocker.Status.ble75NData) {
      //75第N包数据
      console.log("接收到格子柜第N包数据", data, that.data.latticeCabinetData, app.globalData.data75ReceiveTimer);

      if (data) {
        if (!that.data.latticeCabinetData) {
          that.data.latticeCabinetData = new Object();
        }
        if (!that.data.latticeCabinetData.doorDataList) {
          that.data.latticeCabinetData.doorDataList = new Array();
        }
        that.data.latticeCabinetData.doorDataList.push(data);
        let doorMaxCount = that.data.latticeCabinetData.latticeData ? parseInt(that.data.latticeCabinetData.latticeData.equStat.maxDoorCount, 16) : 0;
        let getDoorCount = that.data.latticeCabinetData.doorDataList.length;
        if (doorMaxCount == getDoorCount) {
          //已接收完门的总数量
          if (that.data.data75NReceiveTimer) {
            clearTimeout(that.data.data75NReceiveTimer);
          }

          //记录格子柜信息日志
          let mac = that.data.conMac;
          that.data.latticeCabinetData.mac = mac;
          statistic.statisticData("75data", JSON.stringify(that.data.latticeCabinetData));

          //开始请求是否可以开锁          
          let doorNumArr = new Array();
          let doorRfidArr = new Array();
          for (var i = 0; i < getDoorCount; i++) {
            let doorData = that.data.latticeCabinetData.doorDataList[i].doorStat;
            let doorNum = doorData.doorNum;
            let isOnline = doorData.doorStat;
            let rfid = doorData.rfid;
            let binStat = doorData.binStat;
            if (isOnline != 'FF') {
              let num = parseInt(doorNum, 16);
              doorNumArr.push(num);
              let doorRfidStr = num + ":" + rfid + ":" + binStat;
              doorRfidArr.push(doorRfidStr);
            }
          }
          let doorNumStr = doorNumArr.join(',');
          let doorRfidStr = doorRfidArr.join(',');
          that.setData({
            openning_show: false,
            connectDesc: "门状态读取成功,开始请求开锁信息...",
            loading_show: true,
            loading_desc: '请求开锁信息中...',
          });
          //进行开锁
          that.latticeOpen(mac, doorNumStr, doorRfidStr);
        } else {
          let doorNum = parseInt(data.doorStat.doorNum, 16) + 1;
          let doorNumHex = doorNum.toString(16);
          doorNumHex = doorNumHex.length == 1 ? "0" + doorNumHex : doorNumHex;
          that.setData({
            openning_show: false,
            connectDesc: "数读设备成功,读取格子状态中" + doorNumHex + "...",
            loading_show: true,
            loading_desc: '读取格子状态中' + doorNumHex + '...',
          });
          setTimeout(() => {
            that.send75Command(doorNumHex);
          }, 100);

        }
      } else {
        wx.showModal({
          showCancel: false,
          title: '温馨提示',
          content: '获取锁信息失败,请扫码重试',
          success(res) {}
        })
      }

    } else if (status == BLELocker.Status.ble98Data) {
      //98数据记录
      let dataType = "98data";
      console.log("------data>", data);
      data.push(that.data.mac);
      data.push(that.data.rfid);
      console.log("---98data,", data);

      statistic.statisticData(dataType, JSON.stringify(data));
    } else if (status == BLELocker.Status.bleRecive75Timeout) {
      //蓝牙75第0包接收超时
      wx.showModal({
        showCancel: false,
        title: '温馨提示',
        content: '获取设备信息超时,请扫码重试',
        success(res) {}
      })
    } else if (status == BLELocker.Status.bleRecive75NTimeout) {
      //蓝牙75第N包接收超时
      wx.showModal({
        showCancel: false,
        title: '温馨提示',
        content: '获取锁信息超时,请扫码重试',
        success(res) {}
      })
    } else if (status == BLELocker.Status.bleRecive76Timeout) {
      that.setData({
        loading_show: false,
      });
      //蓝牙75第N包接收超时
      wx.showModal({
        showCancel: false,
        title: '温馨提示',
        content: '开锁响应超时,如果未开门,请扫码重试',
        success(res) {}
      })
    } else if (status == BLELocker.Status.ble76Data) {
      if (app.globalData.data76ReceiveTimer) {
        clearTimeout(app.globalData.data76ReceiveTimer);
        app.globalData.data76ReceiveTimer = null;
      }
      //格子柜开锁结果返回数据
      console.log("格子柜开锁结果返回数据", data);
      that.setData({
        openning_show: false,
        loading_show: false,
      });
      wx.showModal({
        showCancel: false,
        title: '温馨提示',
        content: '门已打开成功，谢谢使用!',
        success(res) {}
      })
      app.globalData.isConnecting = false;
      BLELocker.disconnect('index5445');
      let mac = that.data.conMac;
      data.mac = mac;
      statistic.statisticData("76data", JSON.stringify(data));
    } else if (status == BLELocker.Status.bleOneMorePhyLockStatusData) {
      //one more 陪护椅锁状态信息
      console.log("one more 陪护椅锁状态信息 处理-->", data);
      if (data.hookStatus == 1) {
        //锁舌未弹出,发送锁舌弹出命令后再查询收费规则
        BLELocker.oneMorePhyBleLock();
        setTimeout(() => {
          that.handleStatus(BLELocker.Status.ble95Data, data);
        }, 100);
      } else {
        //相当于95命令，进行收费规则请求然后，点击开锁进行开锁
        that.handleStatus(BLELocker.Status.ble95Data, data);
      }
    } else if (status == BLELocker.Status.bleReciveOneMorePhyTokenTimeout) {
      that.setData({
        loading_show: false,
      });
      //接收one more的陪护椅token超时   
      wx.showModal({
        showCancel: false,
        title: '温馨提示',
        content: '设备token响应超时,请扫码重试',
        success(res) {}
      })
    } else if (status == BLELocker.Status.bleSendOneMorePhyUnlockTimeout) {
      //one more 陪护椅开锁超时
      that.setData({
        loading_show: false,
        openning_show: false,
      });
      //接收one more的陪护椅token超时   
      wx.showModal({
        showCancel: false,
        title: '温馨提示',
        content: '开锁超时,请扫码重试',
        success(res) {}
      })
    } else if (status == BLELocker.Status.bleOneMorePhyUnLockData) {
      //one more 陪护椅开锁结果
      console.log("one more 陪护椅开锁结果：", data);
      that.handleStatus(BLELocker.Status.ble88Data, data);
    } else if (status == BLELocker.Status.bleSend95DevNull || status == BLELocker.Status.bleSend95ConDis) {
      //发送95指令时设备信息为空或蓝牙断开连接
      that.setData({
        loading_show: false,
      });
      app.globalData.isConnecting = false;
      BLELocker.disconnect('index5430');
      that.recordBlueConnectError(ConstantData.err_type.data_95_send_fail, "发送95失败status=" + status);

      //接收one more的陪护椅token超时   
      wx.showModal({
        showCancel: false,
        title: '温馨提示',
        content: '获取设备数据失败,请扫码重试',
        success(res) {}
      })

      clearTimeout(app.globalData.data95ReceiveTimer);
      clearTimeout(app.globalData.auto95RecTimer);
    }

  },
  //格子柜获取开锁结果
  latticeOpen: function (mac, doorNumStr, doorRfidStr) {
    var that = this;
    app.executeRequest(function (header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lattice/open',
        method: 'post',
        header: header,
        data: {
          mac: mac,
          doorNums: doorNumStr,
          doorRfids: doorRfidStr
        },
        success: function (res) {
          console.warn("根据mac获取格子柜开锁结果请求成功", res);
          let isOk = res.data.result === 0;
          if (!isOk) {
            that.data.scanningCode = false;
            let descInfo = res.data.description ? res.data.description + '（' + res.data.result + '）' : '错误编号' + res.data.result;
            that.setData({
              loading_show: false,
              modal: {
                modal_show: true,
                desc: descInfo,
                confirm: true
              }
            })
            that.recordBlueConnectError(ConstantData.err_type.lattice_open_fail, 'mac=' + mac + ';res:' + JSON.stringify(res));
            return;
          } else {
            if (!res.data.doorNum && !res.data.data) {
              that.recordBlueConnectError(ConstantData.err_type.lattice_open_result_err, '返回参数为空mac=' + mac + ';res:' + JSON.stringify(res));
              that.setData({
                loading_show: false,
                modal: {
                  modal_show: true,
                  desc: "设备配置错误！",
                  confirm: true
                }
              })
              return;
            }
            if (res.data.data) {
              let resultData = res.data.data;
              if (resultData.lockType == '直行锁') {
                if (resultData.typeInfoList && resultData.typeInfoList.length == 0) {
                  that.recordBlueConnectError(ConstantData.err_type.lattice_open_result_no_equ, '桩上无设备mac=' + mac + ';res:' + JSON.stringify(res));
                  that.setData({
                    loading_show: false,
                    modal: {
                      modal_show: true,
                      desc: "桩上无设备!",
                      confirm: true
                    }
                  })
                  return;
                }
                console.log("直行锁数据-->", resultData);
                that.setData({
                  lockTypeSeledId: 0,
                  selTypeList: resultData.typeInfoList,
                  directLockSelFlg: true,
                  loading_show: false,
                  modal: {
                    modal_show: true,
                    confirm: false,
                    confirmSelType: true
                  }
                })

              } else {
                that.recordBlueConnectError(ConstantData.err_type.lattice_open_result_err, '锁类型不存在mac=' + mac + ';res:' + JSON.stringify(res));
                that.setData({
                  loading_show: false,
                  modal: {
                    modal_show: true,
                    desc: "设备类型不存在！",
                    confirm: true
                  }
                })
              }
              return;
            }
            //发送开锁指令
            that.send76Command(res.data.doorNum);

          }

        },
        fail: function (res) {
          console.log("根据mac获取格子柜开锁结果请求失败", res)
          that.data.scanningCode = false;
          let netErr = app.handleRes(res, that);
          if (netErr) {
            return
          }
          that.setData({
            loading_show: false,
            modal: {
              modal_show: true,
              desc: '请重新扫码-' + ConstantData.err_type.lattice_open_fail,
              confirm: true
            }
          })
          that.recordBlueConnectError(ConstantData.err_type.lattice_open_fail, 'mac=' + mac + ';res:' + JSON.stringify(res));
        }
      })

    })
  },
  //点击选中设备类型
  selTypeClick: function (e) {
    var that = this;
    console.log("选择的设备类型：", e);
    let selData = e.currentTarget.dataset.data;
    that.setData({
      lockTypeSeledId: selData.categoryId
    });
    that.data.lockSelTypeData = selData;
    //点击租赁后调用创建订单的接口生成订单并进行开锁

  },
  //确定选好设备类型开始进行租赁
  confirmSelLockType: function () {
    var that = this;
    let mac = that.data.conMac;
    let selData = that.data.lockSelTypeData;
    //默认开关等均为正确的值，直行锁目前没有开关状态上报
    that.data.hookStatus = 0;
    that.data.switchStatus = 1;
    that.data.didiStat = 1;
    that.data.rfidIsCache = 0;
    that.setData({
      confirmSelType: false
    })
    //调用open_lock接口获取收费规则
    that.openOrReturnEquitment(selData.selRfid, mac, '0');
    that.hideModal1();
  },

  tipBtnClick: function () {
    this.setData({
      tipStatus: false,
      mapShowStatus: true
    })
  },
  /**
   * 蓝牙连接超时提示信息(目前没有用到)
   */
  blueConTimeOutTip: function () {
    var that = this
    app.executeRequest(function (header) {
      var phoneArr = that.data.serverBasiceConfig.customerService
      var phoneStr = ""
      var mainPhone = phoneArr[0]

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/support/blueTimeoutTip',
        method: 'post',
        header: header,
        success: function (res) {
          let netErr = app.handleRes(res, that);
          if (netErr) {
            return
          }
          if (!res.data) {
            //不存在未归还的设备
            that.blueTimeoutNoAuth()

          } else {
            //存在未归还的设备
            var desc = res.data + " 客服电话:" + mainPhone
            //记录未归还的时间记录
            that.recordReturnBlueTimeoutError(1, '')
            var nophone = app.getUserLoginNoPhone();
            if (nophone == null || nophone == undefined || nophone == 1) {
              wx.setStorageSync("alertBoxTipContent", desc);
              that.setData({
                phoneAuthStatus: true,
                phoneAuthBtt: 'no_return_blue_timeout',
                loading_show: false
              });
              wx.showToast({
                title: '请先登录',
                icon: 'none'
              })
              return;
            } else {
              that.setData({
                loading_show: false,
                alertBoxStatus: true,
                alertBoxTipContent: desc,
                alertBoxBtnName: "确 定"
              })
            }

          }

        },
        fail: function (res) {
          that.blueTimeoutReScanTip()
        }
      })
    })
  },
  /**
   * 蓝牙连接失败没有系统定位权限是否开启提示
   */
  blueTimeoutNoAuth: function () {
    var that = this
    let systeminfo = wx.getStorageSync('systeminfo')
    if (systeminfo) {
      var verArr = systeminfo.version.split(".")
      var sys = systeminfo.system.toLowerCase();
      var flg = false
      if (verArr[0] < 6) {
        flg = true
      } else if (verArr[0] == 6) {
        if (verArr[1] < 5) {
          flg = true
        } else if (verArr[1] == 5) {
          if (verArr[2] < 11) {
            flg = true
          }
        }
      }

      var sysFlg = false
      var sysLocationFlg = false
      if (sys.indexOf("android") != -1) {
        sys = sys.replace("android", "").trim()
        var sysVerArr = sys.split(".")
        console.log(sysVerArr)
        if (sysVerArr[0] < 5) {
          sysFlg = true
        }

        if (sysVerArr[0] >= 6 && sysVerArr[0] < 7) {
          sysLocationFlg = true;
        }
      }

      if (sysFlg) {
        that.setData({
          loading_show: false,
          alertBoxStatus: true,
          alertBoxTipContent: "安卓版本低于5.0,无法完成租赁",
          alertBoxBtnName: "确 定"
        })
      } else if (flg) { //6.5.11
        that.setData({
          loading_show: false,
          alertBoxStatus: true,
          alertBoxTipContent: "微信版本低,请升级微信后租赁",
          alertBoxBtnName: "确 定"
        })
      } else {
        that.blueTimeoutReScanTip()
      }
      return
    }
    wx.getSystemInfo({
      success: function (res) {
        var verArr = res.version.split(".")
        var sys = res.system.toLowerCase();
        var flg = false
        if (verArr[0] < 6) {
          flg = true
        } else if (verArr[0] == 6) {
          if (verArr[1] < 5) {
            flg = true
          } else if (verArr[1] == 5) {
            if (verArr[2] < 11) {
              flg = true
            }
          }
        }

        var sysFlg = false
        var sysLocationFlg = false
        if (sys.indexOf("android") != -1) {
          sys = sys.replace("android", "").trim()
          var sysVerArr = sys.split(".")
          console.log(sysVerArr)
          if (sysVerArr[0] < 5) {
            sysFlg = true
          }

          if (sysVerArr[0] >= 6 && sysVerArr[0] < 7) {
            sysLocationFlg = true;
          }
        }

        //判断是否为特殊机型,暂时不做系统版本判断
        var phoneType = res.model
        // var specialPhoneFlg = isSpecialPhone(phoneType, that)
        if (sysFlg) {
          that.setData({
            loading_show: false,
            alertBoxStatus: true,
            alertBoxTipContent: "安卓版本低于5.0,无法完成租赁",
            alertBoxBtnName: "确 定"
          })
        } else if (flg) { //6.5.11
          that.setData({
            loading_show: false,
            alertBoxStatus: true,
            alertBoxTipContent: "微信版本低,请升级微信后租赁",
            alertBoxBtnName: "确 定"
          })
        } else {
          that.blueTimeoutReScanTip()
        }
      },
      fail: function (res) {
        that.blueTimeoutReScanTip()
      }
    });
  },
  /**
   * 蓝牙连接超时，重新扫码提示弹框
   */
  blueTimeoutReScanTip: function () {
    var that = this
    var blue_fail_time = wx.getStorageSync('blue_fail_time') - 1;
    let pile_id = that.data.pile_id ? 'Z' + that.data.pile_id : '';
    if (blue_fail_time > 2) { //第三次失败就提示
      that.hideModal1();
      let eDesc = getTimeoutReasonDesc();
      var desc = "未找到扫码的桩,请换一个设备租赁";
      var desc_mini = 'STO搜索不成功,请确保设备' + pile_id + '在您附近,(' + that.data.phoneInfo + '-100348)';
      var contact = false
      var confirm = true
      //归位桩存在问题
      that.data.modal.desc = desc
      that.data.modal.desc_mini = desc_mini
      that.data.modal.contact = contact
      that.data.modal.confirm = confirm
      that.data.modal.modal_show = true
      that.setData({
        modal: that.data.modal
      })
      that.recordBlueConnectError(100348, "modalErr:3次及以上连接超时");
      return
    } else {
      let eDesc = getTimeoutReasonDesc();
      that.hideModal1()
      that.data.modal.desc = "未找到扫码的桩,请关闭蓝牙再打开后重试";
      that.data.modal.desc_mini = 'STO搜索不成功,请确保设备' + pile_id + '在您附近,(' + that.data.phoneInfo + '-100347)';
      that.data.modal.retryConnect = true
      that.data.modal.modal_show = true
      that.setData({
        modal: that.data.modal
      })
      that.recordBlueConnectError(100347, "modalErr:连接超时");
      return
    }
  },
  /**
   * 记录蓝牙连接的日志
   */
  connectLog: function (data) {

    if (this.data.connectLogSwitch != 0) {
      return
    }

    var that = this
    data.homingPileBlueName = that.data.curBlueName, //归位桩的蓝牙名称,最长100个字
      data.phoneOs = that.data.systemInfo.system, //手机系统信息,最长245
      data.weixinVer = that.data.systemInfo.version, //微信版本号,最长45
      data.weixinBaseVer = that.data.systemInfo.SDKVersion //微信小程序基库版本
    data.reqNumber = that.data.connectReqNum + 1 //请求的序列号
    data.ctime = Date.parse(new Date()) //客户端的本地当前时间戳
    that.data.connectReqNum = data.reqNumber

    app.executeRequest(function (header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/log/bluet_connect',
        header: header,
        data: data,
        success: function () {}
      })

    })


  },
  /**
   * 去退押金
   */
  toRefundDeposit: function () {
    let that = this;
    var nophone = app.getUserLoginNoPhone();
    if (nophone == null || nophone == undefined || nophone == 1) {
      that.setData({
        phoneAuthStatus: true,
        phoneAuthBtt: 'deposit_record',
        loading_show: false
      });
      that.toWxLogin();
      // wx.showToast({
      //   title: '请先登录',
      //   icon: 'none'
      // })
      return
    }
    wx.navigateTo({
      url: '../user_record/deposit/user_deposit',
    })
  },
  /**
   * 获取基本的配置信息
   */
  getBasicConfigInfo() {
    var that = this



    // app.executeRequest(function(header) {

    var systemInfo = wx.getStorageSync('systeminfo')
    var phoneType = ''
    if (systemInfo) {
      phoneType = systemInfo.model
    }
    wx.request({
      url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/support/base_config',
      method: 'post',
      header: app.getHeader(),
      data: {
        phoneType: phoneType
      },
      success: function (res) {
        let netErr = app.handleRes(res, that);
        if (netErr) {
          return
        }
        console.log('base_config-', res)
        let isJson = common.isJSON(res.data);
        if (!isJson) {
          that.recordBlueConnectError(ConstantData.err_type.errResJson, "非json:/lease/support/base_config:" + JSON.stringify(res));
          return;
        }
        var config = JSON.parse(res.data)
        console.log('base_config-->', config, isJson);

        // 如果服务器返回了登录页面默认是否勾选同意按钮的配置，则将服务器下发的配置覆盖保存到本地全局配置
        if (config.defCheckAgreeService != undefined) {
          app.globalData.defCheckAgreeService = config.defCheckAgreeService == 1
        }
        if (config.connectDelayed.BlueServiceDelayTimeLen > 0) {
          config.connectDelayed.getBLEDeviceServices = config.connectDelayed.BlueServiceDelayTimeLen
        }
        if (config.connectDelayed.Blue95Interval > 0) {
          that.data.blue95Interval = config.connectDelayed.Blue95Interval
        }
        if (config.connectDelayed.AdapterRespTime > 0) {
          that.data.AdapterRespTime = config.connectDelayed.AdapterRespTime
        }
        if (config.connectDelayed.Many95DataInterval > 0) {
          that.data.many95DataInterval = config.connectDelayed.Many95DataInterval
        }

        if (config.miniBeeConfig) {
          app.globalData.miniBeeConfig = config.miniBeeConfig
        } else {
          app.globalData.miniBeeConfig = null;
        }

        console.log('【小蜜蜂广告配置】缓存的广告配置...' + JSON.stringify(app.globalData.miniBeeConfig))

        // 小蜜蜂广告配置---end

        app.globalData.onErrorTimes = config.onErrorTimes || 0;
        that.data.serverBasiceConfig = config;
        that.data.connectLogSwitch = config.connectLogSwitch;
        that.data.homeDepositTime = config.home_deposit_time;
        that.data.blueErrDesc = config.wx_blue_err_desc;
        that.data.isRefundTip = config.is_refund_tip;
        // that.data.wxScore= config.wx_score;
        that.setData({
          wxScore: config.wx_score
        })
        //设置需要提示的机型信息
        ConstantData.setShowHelpImg(config.specialPhoneHelp)

        if (phoneType) {
          isSpecialPhone(phoneType, that)
        }

        console.log("服务的配置信息:", config)
      }
    })

    // })


  },
  hideLeaseTip: function () {
    console.log("---that>", getApp().globalData._that ? 'true' : 'false')
    app.globalData.isConnecting = false;
    BLELocker.disconnect('index3954');
    this.setData({
      showModalStatus: false
    })
  },

  /**
   * 联系客服
   */
  concatService: function () {
    wx.makePhoneCall({
      phoneNumber: '4006710500'
    })
  },
  /**
   * 重试95
   */
  retry95() {
    console.log("重试读取95数据----")
    let that = this
    if (that.data.trying) {
      return
    }
    that.data.trying = true
    setTimeout(() => {
      that.data.trying = false
    }, 3000)
    that.hideModal1()
    console.log("重试读取95数据----aaa")
    that.setData({
      loading_show: true,
      loading_desc: "数据读取重试中"
    });
    console.log("重试读取95数据----bbb")
    that.data.retry95Flg = true;
    this.send95Command();
  },
  /**
   * 重试蓝牙连接
   */
  retryConnect() {
    let that = this
    if (that.data.trying) {
      return
    }
    that.data.trying = true
    that.data.retryConTimer = setTimeout(() => {
      that.data.trying = false
      that.setData({
        retryConBtnCss: "modal-btn-green",
      });
    }, 3000)
    that.hideModal1()
    that.setData({
      retryConBtnCss: "modal-btn-gray",
      loading_show: true,
      loading_desc: "开始重试连接..."
    });
    that.data.retryCon = true;
    common.conTimeCountSeconds(that);
    that.connectBLEDevice(that.data.curBlueName)
  },
  /**
   * 重试归还
   */
  reTryBack: function () {
    let that = this
    if (that.data.trying) {
      return
    }
    that.data.trying = true
    setTimeout(() => {
      that.data.trying = false
    }, 3000)
    this.hideModal1()
    this.setData({
      lockStatTip: false,
      loading_show: true,
      loading_desc: "数据读取重试中"
    });
    this.send95Command();
  },

  /**
   * 重试租赁
   */
  reTryLease: function () {
    let that = this
    if (that.data.trying) {
      return
    }
    that.data.trying = true
    setTimeout(() => {
      that.data.trying = false
    }, 3000)
    this.hideModal1()
    this.setData({
      leaseLockStatTip: false,
      loading_show: true,
      loading_desc: "数据读取重试中",
      connectDesc: "数据读取中"
    })
    this.send95Command();
  },
  bindscroll:function(e) {
    if (!this.data.isSlide) {
      this.getApageLeaseRecord()
      this.data.isSlide=1
    }
  },
  cancelLockStatTip: function () {
    this.setData({
      lockStatTip: false,
      leaseLockStatTip: false
    })
    app.globalData.isConnecting = false;
    BLELocker.disconnect('index4054');
  },

  toViewNoDepositProtocol: function () {
    this.setData({
      hideIsDisconnectStat: false
    })
    wx.navigateTo({
      url: '../../pkgBak/pages/help/protocol/wx_no_deposit/wx_no_deposit',
    })
  },

  toViewLeaseProtocol: function () {
    this.setData({
      hideIsDisconnectStat: false
    })
    wx.navigateTo({
      url: '../../pkgBak/pages/help/lease/lease',
    })
  },
  toHelp: function () {
    wx.navigateTo({
      url: '../../pkgBak/pages/help/help',
    })
  },
  goUserCenter: function () {
    wx.navigateTo({
      url: '../user_center/user_center',
    })
  },
  goUserDeposit: function () {
    wx.navigateTo({
      url: '../user_record/deposit/user_deposit',
    })
  },
  goUserLease: function () {
    wx.navigateTo({
      url: '../user_record/lease/user_lease',
    })
  },
  toLocation: function () {
    var qrc = '';
    if (this.data.qrc) {
      qrc = this.data.qrc;
    }
    wx.navigateTo({
      url: '../../pkgBak/pages/help/locations/locations?qrc=' + encodeURIComponent(qrc),
    })
  },
  radioChange: function (e) {
    let that = this
    console.log(e)
    that.setData({
      read: !that.data.read
    })
  },
  startmessage: function (res) {
    console.log("企业微信消息-->", res)
  },
  completemessage: function (res) {
    console.log("企业微信完成回调-->", res)
  },
  //去归还轮椅
  toNoBackTip: function (e) {
    let equId = e.currentTarget.dataset.equId
    let hospitalName = e.currentTarget.dataset.hospitalName
    let positions = e.currentTarget.dataset.positions
    let equType = e.currentTarget.dataset.type
    let orderCode = e.currentTarget.dataset.ordercode
    wx.navigateTo({
      url: '/pages/index/no_back_tip/no_back_tip?equId=' + equId + "&hospitalName=" + hospitalName + '&positions=' + positions + '&pt=user_lease' + '&equType=' + equType + "&orderCode=" + orderCode,
    })
  },
  //点击申请退押金
  refoundDeposit: function (event) {
    var that = this
    var eqTid = event.currentTarget.dataset.eqtid
    var orderCode = event.currentTarget.dataset.ordercode
    var equName = event.currentTarget.dataset.equname
    var deposit = event.currentTarget.dataset.deposit

    that.data.orderCode = orderCode;
    that.data.noSubMpRefundFlg = false;

    that.confirmRefoundDeposit(eqTid, orderCode, equName)
  },
  //发起申请退押金请求
  confirmRefoundDeposit(eqTid, orderCode, equName) {
    var that = this
    wx.showLoading({
      title: '申请中...',
      mask: true
    });
    app.executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_time_card/left_time',
        method: 'post',
        header: header,
        data: {
          eqTid: eqTid
        },
        success: function (res) {
          getApp().hideLoading();
          console.log(res)
          var leftTime = res.data.data
          console.log("----------->leftTime=", leftTime)
          that.setData({
            eqtId: eqTid,
            orderCode: orderCode,
            equName: equName,
          })
          if (leftTime <= 0) {
            console.log("---------------不存在包时卡")
            if (that.data.noSubMpRefundFlg) {
              //直接退押金
              that.toRebundDeposit();
            } else {
              //不存在包时卡时长
              that.setData({
                depositServiceBoxStatus: true,
                eqtId: eqTid,
                orderCode: orderCode,
                equName: equName,
                refundDepositTipInfo: '请确认是否退押金？'
              })
            }

          } else {
            console.log("---------------存在包时卡")
            //存在包时卡时长
            that.setData({
              depositServiceBoxStatus: true,
              eqtId: eqTid,
              orderCode: ordercode,
              equName: equName,
              refundDepositTipInfo: '退押金后包时卡剩余时间将被收回'
            })
          }
        }
      })

    })
  },
  cancleRebund: function () {
    this.setData({
      depositServiceBoxStatus: false
    })
  },
  //申请退押金
  toRebundDeposit: function () {
    wx.showLoading({
      title: '正在处理...',
      mask: true
    });
    this.setData({
      depositServiceBoxStatus: false
    })
    var that = this
    console.log("申请退款----" + that.data.orderCode)

    app.executeRequest(function (header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_dposit/wxmini/refund_d',
        method: 'post',
        header: header,
        data: {
          orderCode: that.data.orderCode
        },
        success: function (res) {
          getApp().hideLoading();
          console.log(res)
          var data = res.data.result
          that.setData({
            supplementPhone: 0,
            depositBoxBtnName: "确  定",
          });
          if (data == 0) {
            that.data.leseList = []
            that.setData({
              loading: true,
              loadingComplete: false,
              pageNum: 1
            });
            if (res.data.description) {
              //银行卡退款提示
              that.setData({
                depositBoxStatus: true,
                msg: res.data.description,
                depositBoxBtnName: "确  定",
                msgType: 0
              });
            }
            that.data.timer = setInterval(() => {
              that.data.leseList = []
              that.setData({
                loading: true,
                loadingComplete: false,
                pageNum: 1
              });
              that.getApageLeaseRecord(1)
            }, 2000)
            that.getApageLeaseRecord()
          } else if (data == 1) {
            var equNum = res.data.data
            var equName = that.data.equName
            that.setData({
              msg: '请确认' + equNum + '号' + equName + '已插入到归位桩,并扫描该轮椅所在桩位上的二维码完成信息更新后再申请退押金',
              msgType: 1,
              depositBoxStatus: true,
              depositBoxBtnName: "去扫码"
            })
          } else if (data == 2) {
            that.setData({
              msg: '有未支付的租金,请去支付',
              msgType: 2,
              depositBoxStatus: true,
              depositBoxBtnName: "确  定"
            })
          } else if (data == 3) {
            that.setData({
              msg: '参数有误，请查证',
              msgType: 0,
              depositBoxStatus: true,
              depositBoxBtnName: "确  定"
            })
          } else if (data == -132) {
            //退款超出频率限制
            var desc = res.data.description
            that.data.leseList = []
            that.setData({
              msg: desc,
              msgType: 0,
              depositBoxStatus: true,
              depositBoxBtnName: "确  定",
              loading: true,
              loadingComplete: false,
              pageNum: 1
            })
            that.getApageLeaseRecord()
          } else if (data == -101) { //需要登录
            that.setData({
              depositBoxStatus: true,
              depositBoxBtnName: "确  定",
              msgType: 3,
              msg: "请使用手机号登录后,再申请",
              supplementPhone: 1
            })
          } else {
            that.setData({
              msg: 'error' + data,
              depositBoxStatus: true,
              depositBoxBtnName: "确  定"
            })
          }
        },
        fail: function (res) {
          getApp().hideLoading();
          console.log("申请退款访问失败")
          console.log(res)
        }
      })

    })
  },
  /**
   * 确定消息提示弹框
   */
  depositsureTip: function () {
    this.setData({
      depositBoxStatus: false
    })
    var msgType = this.data.msgType

    console.log("---------->>msgType=" + msgType)

    if (msgType == 1) {

    } else if (msgType == 2) {

    } else if (msgType == 3) {
      wx.redirectTo({
        url: '../../index/index?pt=nophone',
      });
    }
  },

  //去支付租金
  toPayLease: function (event) {
    var orderCode = event.currentTarget.dataset.ordercode
    this.toPayment(orderCode)
  },
  toPayment: function (orderCode) {
    var that = this
    if (that.data.payStatus) {} else {
      console.log("支付中。。。。")
      return
    }
    that.setData({
      payStatus: false
    })
    console.log("去支付。。。" + orderCode)

    app.executeRequest(function (header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/ejiam/wxmini/unpay/payment',
        method: 'post',
        header: header,
        data: {
          ordernum: orderCode
        },
        success: function (res) {
          var data = res.data
          console.log("支付结果---" + data.result)
          if (data.result == 0) {
            that.setData({
              alertPayment: true,
              msg: data.description,
              pageNum: 1,
              leseList: []
            })
            that.getApageLeaseRecord()
            console.log("刷新支付记录")
          } else if (data.result == -1) {
            console.log("开始微信支付")
            that.toPayWx(orderCode)
          } else {
            that.setData({
              alertPayment: true,
              msg: data.description
            })
          }

        },
        complete: function (res) {
          console.log("恢复支付")
          that.setData({
            payStatus: true
          })
        }
      })

    })

  },
  toPayWx: function (orderCode) {
    var that = this
    console.log("去支付。。。" + orderCode)
    app.toPayValideLogin(orderCode, function (loginCode, orderCode, err) {

      app.executeRequest(function (header) {

        wx.request({
          url: ConstantData.CONSTATNT_DATA.BASE_URL + '/ejiam/wxmini/weixin/pay',
          method: 'post',
          header: header,
          data: {
            orderCode: orderCode,
            loginCode: loginCode,
            wxErr: err
          },
          success: function (res) {
            var data = res.data
            console.log("支付结果---" + data.result)
            if (data.result != 0 || !data.data || !data.data.timeStamp) {
              console.log("租金支付失败----result=" + data.result + ",description=" + data.description)
              that.setData({
                msg: data.description ? data.description : "支付失败",
                alertPayment: true
              })
              return
            }
            wx.requestPayment({
              appId: 'wx0e458dc331e557cc',
              timeStamp: data.data.timeStamp,
              nonceStr: data.data.nonceStr,
              package: data.data.package,
              signType: data.data.signType,
              paySign: data.data.paySign,
              success: function (res) {
                console.log("SUCCESS")
                console.log(res);

                that.setData({
                  pageNum: 1, //每次触发上拉事件，把searchPageNum+1  
                  leseList: []
                });
                that.getApageLeaseRecord();
              },
              fail: function (res) {
                common.recordErrorInfo(ConstantData.err_type.pay_fail, res ? 'ulea-' + JSON.stringify(res) : '');
              },
              complete: function (res) {
                console.log("complete--" + data.data.paySign)
                console.log(res)
              }
            })
          },
          complete: function (res) {
            console.log("恢复支付。。。")
            that.setData({
              payStatus: true
            })
          }
        })

      })

    });

  },
  sureTip: function () {
    this.setData({
      alertPayment: false
    })
  },
  //故障上报
  tofault: function () {
    wx.navigateTo({
      url: '/pkgNew/pages/faultReporting/index',
    })
  },
  //使用指南
  equUseHelpTip: function () {
    wx.navigateTo({
      url: '/pkgBak/pages/help_tip/help_tip',
    })
  },
  //调研有礼
  toSurvey: function () {
    wx.navigateTo({
      url: '/pkgNew/pages/survey/index',
    })
  }
})


function loginHandle(that, passFlg) {
  try {
    var uuid = wx.getStorageSync('uuid');
    if (uuid) {
      console.log("isCehckSession=" + that.data.isCheckSession)
      if (passFlg && that.data.isCheckSession == 0) {
        that.data.isCheckSession = 1
        that.changePass(); //更换令牌
      }
      if (that.data.scanStatus) {
        return
      }

    } else {
      console.log("loginHandle no uuid login")
      that.loginAuth('', '')
    }
  } catch (e) {}
}

/**
 * 添加地图上的按钮图标
 */
function addMapCoin(id, controls, imgPath) {
  if (controls == null || controls == undefined || controls.length == 0) {
    return
  }
  var lastIcon = controls[controls.length - 1]
  var pLeft = lastIcon.position.left
  var pTop = lastIcon.position.top - 60

  var careIcon = {
    id: id,
    iconPath: imgPath,
    position: {
      left: pLeft,
      top: pTop,
      width: 50,
      height: 50
    },
    clickable: true
  }
  controls.push(careIcon)
  return controls
}
/**
 * 图标是否已经存在
 * 0已存在
 * 1不存在
 */
function iconIsExists(id, controls) {

  if (controls == undefined || controls == null) {
    return -1
  }

  for (var i = 0; i < controls.length; i++) {
    var ctrId = controls[i].id
    if (ctrId == id) {
      return 0
    }
  }

  return 1
}

//根据id删除控件
function popContorl(id, controls) {
  var tempControls = new Array()
  for (var i in controls) {
    var con = controls[i]
    if (con.id != id) {
      tempControls.push(con)
    }
  }
  return tempControls
}
/**
 * 处理是否添加图标
 */
function handleAddMapIcon(id, isExists, flg, controls, imgPath) {
  var newControls = null
  if (isExists == 0) {
    //存在
    if (flg) {} else {
      newControls = popContorl(id, controls)
    }
  } else if (isExists == 1) {
    //不存在
    if (flg) {
      newControls = addMapCoin(id, controls, imgPath)
    } else {}
  }
  return newControls
}


function connectCurrentBlue(that) {
  //隐藏可以关闭蓝牙
  that.data.hideIsDisconnectStat = true;
  that.setData({
    openning_show: false
  })
  if (that.data.curBlueName) {
    that.setData({
      loading_show: true,
      loading_desc: '开始连接...',
      agentLeaseSelStatus: false,
      showModalStatus: false
    })
    common.conTimeCountSeconds(that);
    that.connectBLEDevice(that.data.curBlueName)
  }
}

//登录倒计时
function payDepositSecondCountDown(that, total_micro_second) {
  if (that.data.payDepositBtnStatus) {
    console.log("重新支付")
    return;
  }
  if (total_micro_second <= 0) {
    that.setData({
      payDepositBtnTxt: "重新支付",
      payDepositBtnStatus: true
    });
    // timeout则跳出递归
    return;
  }
  // 渲染倒计时时钟
  that.setData({
    payDepositBtnTxt: date_format(total_micro_second) + "秒"
  });

  setTimeout(function () {
    // 放在最后--
    total_micro_second -= 1000;
    payDepositSecondCountDown(that, total_micro_second);
  }, 1000)
}
// 时间格式化输出，如03:25:19 86。每10ms都会调用一次
function date_format(micro_second) {
  // 秒数
  var second = Math.floor(micro_second / 1000);
  // 小时位
  var hr = Math.floor(second / 3600);
  // 分钟位
  var min = fill_zero_prefix(Math.floor((second - hr * 3600) / 60));
  // 秒位
  var sec = fill_zero_prefix((second - hr * 3600 - min * 60)); // equal to => var sec = second % 60;
  // 毫秒位，保留2位
  var micro_sec = fill_zero_prefix(Math.floor((micro_second % 1000) / 10));
  return sec;
}

// 位数不足补零
function fill_zero_prefix(num) {
  return num < 10 ? "0" + num : num
}

/**
 * 判断是否为特殊机型
 */
function isSpecialPhone(phoneType, that) {
  var showImg = ConstantData.getShowHelpImg(phoneType)
  console.log("------------->showImg>" + showImg)
  if (showImg) {
    that.setData({
      phoneSetLocationHelpImg: showImg
    })
    return true
  }
  return false

}

function getBLETimeoutReasonType(that) {
  //判断特殊机型
  var flg = blueErrTipLocation(that);
  let blue_fail_time = wx.getStorageSync('blue_fail_time') || 1;
  wx.setStorageSync('blue_fail_time', blue_fail_time + 1);
  let user_no_back = wx.getStorageSync('user_no_back');
  let errType = '';
  let pile_id = that.data.pile_id ? 'Z' + that.data.pile_id : '';
  if (flg) {
    if (user_no_back) {
      //判断次数
      if (blue_fail_time > 2) {
        errType = 100344;
        var desc = "请确认设备已经锁好且拉不下来后可联系客服帮您归还。";
        var desc_mini = 'SPBT连接不成功 ' + pile_id + '(' + that.data.phoneInfo + '-100344)';
        var contact = true
        var open_location_show = false
        var retryConnect = false
      } else {
        errType = 100342;
        var desc = "请打开定位和微信位置权限后重试。";
        var desc_mini = 'SPBT连接不成功 ' + pile_id + '(' + that.data.phoneInfo + '-100342)';
        var contact = false
        var open_location_show = true
        var retryConnect = true
      }
      that.setData({
        modal: {
          modal_show: true,
          desc: desc,
          desc_mini: desc_mini,
          contact: contact,
          open_location_show: open_location_show,
          retryConnect: retryConnect
        }
      })
    } else {
      //判断次数
      if (blue_fail_time > 2) {
        errType = 100343;
        var desc = "请换一个设备租赁";
        var desc_mini = 'SPBT连接不成功 ' + pile_id + '(' + that.data.phoneInfo + '-100343)';
        var open_location_show = false
        var confirm = true
        var retryConnect = false
      } else {
        errType = 100341;
        var desc = "请打开定位和微信位置权限后重试。";
        var desc_mini = 'SPBT连接不成功 ' + pile_id + '(' + that.data.phoneInfo + '-100341)';
        var open_location_show = true
        var confirm = false
        var retryConnect = true
      }
      that.setData({
        modal: {
          modal_show: true,
          desc: desc,
          desc_mini: desc_mini,
          open_location_show: open_location_show,
          confirm: confirm,
          retryConnect: retryConnect
        }
      })
    }
  } else {
    if (user_no_back) {
      //判断次数
      if (blue_fail_time > 2) {
        errType = 100346;
        var desc = "未找到扫码的桩,请确认设备已经锁好且拉不下来后可联系客服帮您归还。";
        var desc_mini = 'STO搜索不成功,请确保设备' + pile_id + '在您附近(' + that.data.phoneInfo + '-100346)';
        var contact = true
        var confirm = false
      } else {
        errType = 100345;
        var desc = "未找到扫码的桩,请关闭蓝牙再打开后重试";
        var desc_mini = 'STO搜索不成功,请确保设备' + pile_id + '在您附近(' + that.data.phoneInfo + '-100345)';
        var contact = false
        var confirm = true
      }
      that.setData({
        modal: {
          modal_show: true,
          desc: desc,
          desc_mini: desc_mini,
          contact: contact,
          confirm: confirm,
        }
      })
    } else {
      that.blueTimeoutNoAuth()
    }
  }
  if (errType) {
    that.recordBlueConnectError(errType, 'modalErr:连接超时');
  }
}
/**
 * 获取新连接错误标记的错误码
 */
function getTimeoutReasonCode(that) {
  let errDesc = app.globalData.conErrDesc;
  let errCode = '10030';
  if (errDesc) {
    if (errDesc.indexOf('搜索超时') != -1) {

      errCode = '10034';
    } else if (errDesc.indexOf('openAdapterTimeout') != -1) {
      errCode = '100312';
    } else if (errDesc.indexOf('locationAuthTimeout') != -1) {
      errCode = '100313';
    } else if (errDesc.indexOf('openBluetoothAdapter') != -1) {
      let systemInfo = wx.getStorageSync('systeminfo');
      if (systemInfo.system.toLowerCase().indexOf('ios 13') != -1) {
        errCode = '100310';
      } else {
        errCode = '10031';
      }
    } else if (errDesc.indexOf('getBluetoothDevices') != -1) {
      errCode = '10032';
    } else if (errDesc.indexOf('startBluetoothDevicesDiscovery') != -1) {
      errCode = '10033';
    } else if (errDesc.indexOf('createBLEConnection') != -1) {
      errCode = '10035';
    } else if (errDesc.indexOf('getBLEDeviceServices') != -1) {
      errCode = '10036';
    } else if (errDesc.indexOf('getBLEDeviceCharacteristics') != -1) {
      errCode = '10037';
    } else if (errDesc.indexOf('notifyBLECharacteristicValueChanged') != -1) {
      errCode = '10038';
    } else if (errDesc.indexOf('receivingData') != -1) {
      errCode = '10039';
    }
  }
  return errCode;
}
/**
 * 获取新连接错误的标记信息
 */
function getTimeoutReasonDesc() {
  var systemInfo = wx.getStorageSync('systeminfo')
  var phoneType = ''
  if (systemInfo) {
    phoneType = systemInfo.model
  }
  let errDesc = app.globalData.conErrDesc;
  console.log("---->getTimeoutEdesc>", errDesc);
  let eDesc = '';
  if (errDesc) {
    if (errDesc.indexOf('搜索超时') != -1) {
      eDesc = 'searchTimout';
    } else if (errDesc.indexOf('notifyBLECharacteristicValueChanged') != -1) {
      eDesc = 'notifyBLE';
    } else if (errDesc.indexOf('getBLEDeviceCharacteristics') != -1) {
      eDesc = 'getBleDevChar';
    } else if (errDesc.indexOf('getBLEDeviceServices') != -1) {
      eDesc = 'getBleDevServ';
    } else if (errDesc.indexOf('createBLEConnection') != -1) {
      eDesc = 'creaCon';
    } else if (errDesc.indexOf('startBluetoothDevicesDiscovery') != -1) {
      eDesc = 'startDiscover';
    } else if (errDesc.indexOf('getBluetoothDevices') != -1) {
      eDesc = 'getBlueDev';
    } else if (errDesc.indexOf('openBluetoothAdapter') != -1) {
      eDesc = 'openAdapter';
    }
  }
  return phoneType + ':' + eDesc;
}

/**
 * 判断是否需要提示开定位权限
 */
function blueErrTipLocation(that) {
  var systemInfo = wx.getStorageSync('systeminfo')
  // return true
  var phoneType = ''
  if (systemInfo) {
    phoneType = systemInfo.model
  }
  phoneType = phoneType.toLowerCase()
  console.log('phonetype------------------------>', phoneType)
  if (phoneType.indexOf("meizu") != -1) {
    that.setData({
      phoneType: "meizu"
    });
    return true;
  }
  if (phoneType.indexOf("vivo") != -1) {
    that.setData({
      phoneType: "vivo"
    });
    return true;
  }
  if (phoneType.indexOf("oppo") != -1) {
    that.setData({
      phoneType: "oppo"
    });
    return true;
  }
  if (phoneType.indexOf("huawei") != -1) {
    that.setData({
      phoneType: "huawei"
    });
    return true;
  }

  // if (phoneType.indexOf("iphone") != -1) {
  //   that.setData({
  //     phoneType: "meizu"
  //   });
  //   return true;
  // }
  return false;
}
/**
 * 动态小手
 */
// function moveHand(that) {
//   setTimeout(() => {
//      setInterval(() => {
//         that.setData({
//           hand_img:that.data.hand_img=='hand_img1'?'hand_img2':'hand_img1',
//           // bubble_img:that.data.bubble_img=='bubble_img1'?'bubble_img2':'bubble_img1',
//         })
//         // console.log(33333)
//       }, 500);
//   }, 1000)

// }